text
stringlengths
70
351k
source
stringclasses
4 values
<file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> hyperswitch_domain_models macro=ConfigValidate roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> hyperswitch_domain_models macro=ConfigValidate roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> hyperswitch_domain_models macro=ConfigValidate roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> hyperswitch_domain_models macro=ConfigValidate roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/configs.rs" crate="hyperswitch_domain_models" role="use_site"> //! Configs interface use common_enums::ApplicationError; use masking::Secret; use router_derive; use serde::Deserialize; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub cashtocode: ConnectorParams, pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> hyperswitch_domain_models macro=ConfigValidate roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payouts.rs" crate="api_models" role="use_site"> use std::collections::HashMap; use cards::CardNumber; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, pii::{self, Email}, transformers::ForeignFrom, types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub payout_id: Option<String>, // TODO: #1321 https://github.com/juspay/hyperswitch/issues/1321 /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 1000)] #[mandatory_in(PayoutsCreateRequest = u64)] #[remove_in(PayoutsConfirmRequest)] #[serde(default, deserialize_with = "payments::amount::deserialize_option")] pub amount: Option<payments::Amount>, /// The currency of the payout request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] #[mandatory_in(PayoutsCreateRequest = Currency)] #[remove_in(PayoutsConfirmRequest)] pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector #[schema(value_type = Option<RoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] pub routing: Option<serde_json::Value>, /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = Option<bool>, example = true, default = false)] #[remove_in(PayoutConfirmRequest)] pub confirm: Option<bool>, /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = Option<PayoutType>, example = "card")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method information required for carrying out a payout #[schema(value_type = Option<PayoutMethodData>)] pub payout_method_data: Option<PayoutMethodData>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = Option<bool>, example = true, default = false)] pub auto_fulfill: Option<bool>, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<payments::CustomerDetails>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PayoutsCreateRequest)] #[mandatory_in(PayoutConfirmRequest = String)] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = Option<PayoutEntityType>, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, /// Specifies whether or not the payout request is recurring #[schema(value_type = Option<bool>, default = false)] pub recurring: Option<bool>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)] pub payout_token: Option<String>, /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true, value_type = Option<bool>)] pub payout_link: Option<bool>, /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// Identifier for payout method pub payout_method_id: Option<String>, } impl PayoutCreateRequest { pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } } /// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub payout_link_id: Option<String>, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// List of payout methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe #[schema(value_type = Option<bool>, example = false)] pub test_mode: Option<bool>, } /// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), } impl Default for PayoutMethodData { fn default() -> Self { Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AchBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [9 digits] Routing number - used in USA for identifying a specific bank. #[schema(value_type = String, example = "110000000")] pub bank_routing_number: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches. #[schema(value_type = String, example = "98-76-54")] pub bank_sort_code: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer. #[schema(value_type = String, example = "DE89370400440532013000")] pub iban: Secret<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = String, example = "HSBCGB2LXXX")] pub bic: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct PixBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// Unique key for pix customer #[schema(value_type = String, example = "000123456")] pub pix_key: Secret<String>, /// Individual taxpayer identification number #[schema(value_type = Option<String>, example = "000123456")] pub tax_id: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum Wallet { Paypal(Paypal), Venmo(Venmo), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Option<Email>, /// mobile number linked to paypal account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, /// id of the paypal account #[schema(value_type = String, example = "G83KXTJ5EHCQ2")] pub paypal_id: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Venmo { /// mobile number linked to venmo account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, } #[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: String, // TODO: Update this to PayoutIdType similar to PaymentIdType /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")] pub merchant_id: id_type::MerchantId, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 1000)] pub amount: common_utils::types::MinorUnit, /// Recipient's currency for the payout request #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// The connector used for the payout #[schema(example = "wise")] pub connector: Option<String>, /// The payout method that is to be used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method details for the payout #[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{ "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null } }"#))] pub payout_method_data: Option<PayoutMethodDataResponse>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = bool, example = true, default = false)] pub auto_fulfill: bool, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetailsResponse>)] pub customer: Option<payments::CustomerDetailsResponse>, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout #[schema(example = "US", value_type = CountryAlpha2)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout #[schema(example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: api_enums::PayoutEntityType, /// Specifies whether or not the payout request is recurring #[schema(value_type = bool, default = false)] pub recurring: bool, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Unique identifier of the merchant connector account #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, /// If there was an error while calling the connector the error message is received here #[schema(value_type = Option<String>, example = "Failed while verifying the card")] pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(value_type = Option<String>, example = "E0001")] pub error_code: Option<String>, /// The business profile that is associated with this payout #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Time when the payout was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Underlying processor's payout resource ID #[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")] pub connector_transaction_id: Option<String>, /// Payout's send priority (if applicable) #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// List of attempts #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: crypto::OptionalEncryptableName, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, /// Identifier for payout method pub payout_method_id: Option<String>, } /// The payout method information for response #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodDataResponse { #[schema(value_type = CardAdditionalData)] Card(Box<payout_method_utils::CardAdditionalData>), #[schema(value_type = BankAdditionalData)] Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct PayoutAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = PayoutStatus, example = "failed")] pub status: api_enums::PayoutStatus, /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6583)] pub amount: common_utils::types::MinorUnit, /// The currency of the amount of the payout attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, /// The connector used for the payout pub connector: Option<String>, /// Connector's error code in case of failures pub error_code: Option<String>, /// Connector's error message in case of failures pub error_message: Option<String>, /// The payout method that was used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payment_method: Option<api_enums::PayoutType>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "bacs")] pub payout_method_type: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payout provided by the connector pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: String, /// `force_sync` with the connector to get payout details /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[serde(skip_deserializing)] pub payout_id: String, } #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct PayoutVendorAccountDetails { pub vendor_details: PayoutVendorDetails, pub individual_details: PayoutIndividualDetails, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutVendorDetails { pub account_type: String, pub business_type: String, pub business_profile_mcc: Option<i32>, pub business_profile_url: Option<String>, pub business_profile_name: Option<Secret<String>>, pub company_address_line1: Option<Secret<String>>, pub company_address_line2: Option<Secret<String>>, pub company_address_postal_code: Option<Secret<String>>, pub company_address_city: Option<Secret<String>>, pub company_address_state: Option<Secret<String>>, pub company_phone: Option<Secret<String>>, pub company_tax_id: Option<Secret<String>>, pub company_owners_provided: Option<bool>, pub capabilities_card_payments: Option<bool>, pub capabilities_transfers: Option<bool>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutIndividualDetails { pub tos_acceptance_date: Option<i64>, pub tos_acceptance_ip: Option<Secret<String>>, pub individual_dob_day: Option<Secret<String>>, pub individual_dob_month: Option<Secret<String>>, pub individual_dob_year: Option<Secret<String>>, pub individual_id_number: Option<Secret<String>>, pub individual_ssn_last_4: Option<Secret<String>>, pub external_account_account_holder_type: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123")] pub starting_after: Option<String>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123")] pub ending_before: Option<String>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The time at which payout is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListFilterConstraints { /// The identifier for payout #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// The list of currencies to filter payouts list #[schema(value_type = Currency, example = "USD")] pub currency: Option<Vec<api_enums::Currency>>, /// The list of payout status to filter payouts list #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))] pub status: Option<Vec<api_enums::PayoutStatus>>, /// The list of payout methods to filter payouts list #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))] pub payout_method: Option<Vec<common_enums::PayoutType>>, /// Type of recipient #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<common_enums::PayoutEntityType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListResponse { /// The number of payouts included in the list pub size: usize, /// The list of payouts response objects pub data: Vec<PayoutCreateResponse>, /// The total number of available payouts for given constraints #[serde(skip_serializing_if = "Option::is_none")] pub total_count: Option<i64>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListFilters { /// The list of available connector filters #[schema(value_type = Vec<PayoutConnectors>)] pub connector: Vec<api_enums::PayoutConnectors>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<common_enums::Currency>, /// The list of available payout status filters #[schema(value_type = Vec<PayoutStatus>)] pub status: Vec<common_enums::PayoutStatus>, /// The list of available payout method filters #[schema(value_type = Vec<PayoutType>)] pub payout_method: Vec<common_enums::PayoutType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutLinkResponse { pub payout_link_id: String, #[schema(value_type = String)] pub link: Secret<url::Url>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PayoutLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, pub payout_id: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkDetails { pub publishable_key: Secret<String>, pub client_secret: Secret<String>, pub payout_link_id: String, pub payout_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutEnabledPaymentMethodsInfo { pub payment_method: common_enums::PaymentMethod, pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodTypeInfo { pub payment_method_type: common_enums::PaymentMethodType, pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } #[derive(Clone, Debug, serde::Serialize, FlatStruct)] pub struct RequiredFieldsOverrideRequest { pub billing: Option<payments::Address>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, pub payout_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, pub error_code: Option<UnifiedCode>, pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, } impl From<Bank> for payout_method_utils::BankAdditionalData { fn from(bank_data: Bank) -> Self { match bank_data { Bank::Ach(AchBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_routing_number, }) => Self::Ach(Box::new( payout_method_utils::AchBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_routing_number: bank_routing_number.into(), }, )), Bank::Bacs(BacsBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_sort_code, }) => Self::Bacs(Box::new( payout_method_utils::BacsBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_sort_code: bank_sort_code.into(), }, )), Bank::Sepa(SepaBankTransfer { bank_name, bank_country_code, bank_city, iban, bic, }) => Self::Sepa(Box::new( payout_method_utils::SepaBankTransferAdditionalData { bank_name, bank_country_code, bank_city, iban: iban.into(), bic: bic.map(From::from), }, )), Bank::Pix(PixBankTransfer { bank_name, bank_branch, bank_account_number, pix_key, tax_id, }) => Self::Pix(Box::new( payout_method_utils::PixBankTransferAdditionalData { bank_name, bank_branch, bank_account_number: bank_account_number.into(), pix_key: pix_key.into(), tax_id: tax_id.map(From::from), }, )), } } } impl From<Wallet> for payout_method_utils::WalletAdditionalData { fn from(wallet_data: Wallet) -> Self { match wallet_data { Wallet::Paypal(Paypal { email, telephone_number, paypal_id, }) => Self::Paypal(Box::new(payout_method_utils::PaypalAdditionalData { email: email.map(ForeignFrom::foreign_from), telephone_number: telephone_number.map(From::from), paypal_id: paypal_id.map(From::from), })), Wallet::Venmo(Venmo { telephone_number }) => { Self::Venmo(Box::new(payout_method_utils::VenmoAdditionalData { telephone_number: telephone_number.map(From::from), })) } } } } impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { payout_method_utils::AdditionalPayoutMethodData::Card(card_data) => { Self::Card(card_data) } payout_method_utils::AdditionalPayoutMethodData::Bank(bank_data) => { Self::Bank(bank_data) } payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } } } }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/api_models/src/payouts.rs" crate="api_models" role="use_site"> use std::collections::HashMap; use cards::CardNumber; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, pii::{self, Email}, transformers::ForeignFrom, types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub payout_id: Option<String>, // TODO: #1321 https://github.com/juspay/hyperswitch/issues/1321 /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 1000)] #[mandatory_in(PayoutsCreateRequest = u64)] #[remove_in(PayoutsConfirmRequest)] #[serde(default, deserialize_with = "payments::amount::deserialize_option")] pub amount: Option<payments::Amount>, /// The currency of the payout request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] #[mandatory_in(PayoutsCreateRequest = Currency)] #[remove_in(PayoutsConfirmRequest)] pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector #[schema(value_type = Option<RoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] pub routing: Option<serde_json::Value>, /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = Option<bool>, example = true, default = false)] #[remove_in(PayoutConfirmRequest)] pub confirm: Option<bool>, /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = Option<PayoutType>, example = "card")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method information required for carrying out a payout #[schema(value_type = Option<PayoutMethodData>)] pub payout_method_data: Option<PayoutMethodData>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = Option<bool>, example = true, default = false)] pub auto_fulfill: Option<bool>, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<payments::CustomerDetails>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PayoutsCreateRequest)] #[mandatory_in(PayoutConfirmRequest = String)] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = Option<PayoutEntityType>, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, /// Specifies whether or not the payout request is recurring #[schema(value_type = Option<bool>, default = false)] pub recurring: Option<bool>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)] pub payout_token: Option<String>, /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true, value_type = Option<bool>)] pub payout_link: Option<bool>, /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// Identifier for payout method pub payout_method_id: Option<String>, } impl PayoutCreateRequest { pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } } /// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub payout_link_id: Option<String>, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// List of payout methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe #[schema(value_type = Option<bool>, example = false)] pub test_mode: Option<bool>, } /// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), } impl Default for PayoutMethodData { fn default() -> Self { Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AchBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [9 digits] Routing number - used in USA for identifying a specific bank. #[schema(value_type = String, example = "110000000")] pub bank_routing_number: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches. #[schema(value_type = String, example = "98-76-54")] pub bank_sort_code: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer. #[schema(value_type = String, example = "DE89370400440532013000")] pub iban: Secret<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = String, example = "HSBCGB2LXXX")] pub bic: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct PixBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// Unique key for pix customer #[schema(value_type = String, example = "000123456")] pub pix_key: Secret<String>, /// Individual taxpayer identification number #[schema(value_type = Option<String>, example = "000123456")] pub tax_id: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum Wallet { Paypal(Paypal), Venmo(Venmo), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Option<Email>, /// mobile number linked to paypal account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, /// id of the paypal account #[schema(value_type = String, example = "G83KXTJ5EHCQ2")] pub paypal_id: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Venmo { /// mobile number linked to venmo account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, } #[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: String, // TODO: Update this to PayoutIdType similar to PaymentIdType /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")] pub merchant_id: id_type::MerchantId, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 1000)] pub amount: common_utils::types::MinorUnit, /// Recipient's currency for the payout request #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// The connector used for the payout #[schema(example = "wise")] pub connector: Option<String>, /// The payout method that is to be used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method details for the payout #[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{ "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null } }"#))] pub payout_method_data: Option<PayoutMethodDataResponse>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = bool, example = true, default = false)] pub auto_fulfill: bool, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetailsResponse>)] pub customer: Option<payments::CustomerDetailsResponse>, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout #[schema(example = "US", value_type = CountryAlpha2)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout #[schema(example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: api_enums::PayoutEntityType, /// Specifies whether or not the payout request is recurring #[schema(value_type = bool, default = false)] pub recurring: bool, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Unique identifier of the merchant connector account #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, /// If there was an error while calling the connector the error message is received here #[schema(value_type = Option<String>, example = "Failed while verifying the card")] pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(value_type = Option<String>, example = "E0001")] pub error_code: Option<String>, /// The business profile that is associated with this payout #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Time when the payout was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Underlying processor's payout resource ID #[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")] pub connector_transaction_id: Option<String>, /// Payout's send priority (if applicable) #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// List of attempts #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: crypto::OptionalEncryptableName, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, /// Identifier for payout method pub payout_method_id: Option<String>, } /// The payout method information for response #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodDataResponse { #[schema(value_type = CardAdditionalData)] Card(Box<payout_method_utils::CardAdditionalData>), #[schema(value_type = BankAdditionalData)] Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct PayoutAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = PayoutStatus, example = "failed")] pub status: api_enums::PayoutStatus, /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6583)] pub amount: common_utils::types::MinorUnit, /// The currency of the amount of the payout attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, /// The connector used for the payout pub connector: Option<String>, /// Connector's error code in case of failures pub error_code: Option<String>, /// Connector's error message in case of failures pub error_message: Option<String>, /// The payout method that was used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payment_method: Option<api_enums::PayoutType>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "bacs")] pub payout_method_type: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payout provided by the connector pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: String, /// `force_sync` with the connector to get payout details /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[serde(skip_deserializing)] pub payout_id: String, } #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct PayoutVendorAccountDetails { pub vendor_details: PayoutVendorDetails, pub individual_details: PayoutIndividualDetails, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutVendorDetails { pub account_type: String, pub business_type: String, pub business_profile_mcc: Option<i32>, pub business_profile_url: Option<String>, pub business_profile_name: Option<Secret<String>>, pub company_address_line1: Option<Secret<String>>, pub company_address_line2: Option<Secret<String>>, pub company_address_postal_code: Option<Secret<String>>, pub company_address_city: Option<Secret<String>>, pub company_address_state: Option<Secret<String>>, pub company_phone: Option<Secret<String>>, pub company_tax_id: Option<Secret<String>>, pub company_owners_provided: Option<bool>, pub capabilities_card_payments: Option<bool>, pub capabilities_transfers: Option<bool>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutIndividualDetails { pub tos_acceptance_date: Option<i64>, pub tos_acceptance_ip: Option<Secret<String>>, pub individual_dob_day: Option<Secret<String>>, pub individual_dob_month: Option<Secret<String>>, pub individual_dob_year: Option<Secret<String>>, pub individual_id_number: Option<Secret<String>>, pub individual_ssn_last_4: Option<Secret<String>>, pub external_account_account_holder_type: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123")] pub starting_after: Option<String>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123")] pub ending_before: Option<String>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The time at which payout is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListFilterConstraints { /// The identifier for payout #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// The list of currencies to filter payouts list #[schema(value_type = Currency, example = "USD")] pub currency: Option<Vec<api_enums::Currency>>, /// The list of payout status to filter payouts list #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))] pub status: Option<Vec<api_enums::PayoutStatus>>, /// The list of payout methods to filter payouts list #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))] pub payout_method: Option<Vec<common_enums::PayoutType>>, /// Type of recipient #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<common_enums::PayoutEntityType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListResponse { /// The number of payouts included in the list pub size: usize, /// The list of payouts response objects pub data: Vec<PayoutCreateResponse>, /// The total number of available payouts for given constraints #[serde(skip_serializing_if = "Option::is_none")] pub total_count: Option<i64>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListFilters { /// The list of available connector filters #[schema(value_type = Vec<PayoutConnectors>)] pub connector: Vec<api_enums::PayoutConnectors>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<common_enums::Currency>, /// The list of available payout status filters #[schema(value_type = Vec<PayoutStatus>)] pub status: Vec<common_enums::PayoutStatus>, /// The list of available payout method filters #[schema(value_type = Vec<PayoutType>)] pub payout_method: Vec<common_enums::PayoutType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutLinkResponse { pub payout_link_id: String, #[schema(value_type = String)] pub link: Secret<url::Url>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PayoutLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, pub payout_id: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkDetails { pub publishable_key: Secret<String>, pub client_secret: Secret<String>, pub payout_link_id: String, pub payout_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutEnabledPaymentMethodsInfo { pub payment_method: common_enums::PaymentMethod, pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodTypeInfo { pub payment_method_type: common_enums::PaymentMethodType, pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } #[derive(Clone, Debug, serde::Serialize, FlatStruct)] pub struct RequiredFieldsOverrideRequest { pub billing: Option<payments::Address>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, pub payout_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, pub error_code: Option<UnifiedCode>, pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, } impl From<Bank> for payout_method_utils::BankAdditionalData { fn from(bank_data: Bank) -> Self { match bank_data { Bank::Ach(AchBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_routing_number, }) => Self::Ach(Box::new( payout_method_utils::AchBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_routing_number: bank_routing_number.into(), }, )), Bank::Bacs(BacsBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_sort_code, }) => Self::Bacs(Box::new( payout_method_utils::BacsBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_sort_code: bank_sort_code.into(), }, )), Bank::Sepa(SepaBankTransfer { bank_name, bank_country_code, bank_city, iban, bic, }) => Self::Sepa(Box::new( payout_method_utils::SepaBankTransferAdditionalData { bank_name, bank_country_code, bank_city, iban: iban.into(), bic: bic.map(From::from), }, )), Bank::Pix(PixBankTransfer { bank_name, bank_branch, bank_account_number, pix_key, tax_id, }) => Self::Pix(Box::new( payout_method_utils::PixBankTransferAdditionalData { bank_name, bank_branch, bank_account_number: bank_account_number.into(), pix_key: pix_key.into(), tax_id: tax_id.map(From::from), }, )), } } } impl From<Wallet> for payout_method_utils::WalletAdditionalData { fn from(wallet_data: Wallet) -> Self { match wallet_data { Wallet::Paypal(Paypal { email, telephone_number, paypal_id, }) => Self::Paypal(Box::new(payout_method_utils::PaypalAdditionalData { email: email.map(ForeignFrom::foreign_from), telephone_number: telephone_number.map(From::from), paypal_id: paypal_id.map(From::from), })), Wallet::Venmo(Venmo { telephone_number }) => { Self::Venmo(Box::new(payout_method_utils::VenmoAdditionalData { telephone_number: telephone_number.map(From::from), })) } } } } impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { payout_method_utils::AdditionalPayoutMethodData::Card(card_data) => { Self::Card(card_data) } payout_method_utils::AdditionalPayoutMethodData::Bank(bank_data) => { Self::Bank(bank_data) } payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } } } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=PolymorphicSchema roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &PaymentsCancelRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, ], "reject", )?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id()) }) .ok() } else { None }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _should_decline_transaction: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate { status: enums::IntentStatus::Failed, merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()), updated_by: storage_scheme.to_string(), }; let (error_code, error_message) = payment_data .frm_message .clone() .map_or((None, None), |fraud_check| { ( Some(Some(fraud_check.frm_status.to_string())), Some(fraud_check.frm_reason.map(|reason| reason.to_string())), ) }); let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate { status: enums::AttemptStatus::Failure, error_code, error_message, updated_by: storage_scheme.to_string(), }; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, intent_status_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), attempt_status_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let error_code = payment_data.payment_attempt.error_code.clone(); let error_message = payment_data.payment_attempt.error_message.clone(); req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentReject { error_code, error_message, })) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsCancelRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &PaymentsCancelRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, ], "reject", )?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id()) }) .ok() } else { None }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _should_decline_transaction: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate { status: enums::IntentStatus::Failed, merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()), updated_by: storage_scheme.to_string(), }; let (error_code, error_message) = payment_data .frm_message .clone() .map_or((None, None), |fraud_check| { ( Some(Some(fraud_check.frm_status.to_string())), Some(fraud_check.frm_reason.map(|reason| reason.to_string())), ) }); let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate { status: enums::AttemptStatus::Failure, error_code, error_message, updated_by: storage_scheme.to_string(), }; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, intent_status_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), attempt_status_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let error_code = payment_data.payment_attempt.error_code.clone(); let error_message = payment_data.payment_attempt.error_message.clone(); req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentReject { error_code, error_message, })) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsCancelRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &PaymentsCancelRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, ], "reject", )?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id()) }) .ok() } else { None }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _should_decline_transaction: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate { status: enums::IntentStatus::Failed, merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()), updated_by: storage_scheme.to_string(), }; let (error_code, error_message) = payment_data .frm_message .clone() .map_or((None, None), |fraud_check| { ( Some(Some(fraud_check.frm_status.to_string())), Some(fraud_check.frm_reason.map(|reason| reason.to_string())), ) }); let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate { status: enums::AttemptStatus::Failure, error_code, error_message, updated_by: storage_scheme.to_string(), }; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, intent_status_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), attempt_status_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let error_code = payment_data.payment_attempt.error_code.clone(); let error_message = payment_data.payment_attempt.error_message.clone(); req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentReject { error_code, error_message, })) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsCancelRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &PaymentsCancelRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, ], "reject", )?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, merchant_id, merchant_account.storage_scheme, ) .await?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id()) }) .ok() } else { None }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _should_decline_transaction: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate { status: enums::IntentStatus::Failed, merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()), updated_by: storage_scheme.to_string(), }; let (error_code, error_message) = payment_data .frm_message .clone() .map_or((None, None), |fraud_check| { ( Some(Some(fraud_check.frm_status.to_string())), Some(fraud_check.frm_reason.map(|reason| reason.to_string())), ) }); let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate { status: enums::AttemptStatus::Failure, error_code, error_message, updated_by: storage_scheme.to_string(), }; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, intent_status_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), attempt_status_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let error_code = payment_data.payment_attempt.error_code.clone(); let error_message = payment_data.payment_attempt.error_message.clone(); req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentReject { error_code, error_message, })) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsCancelRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsIncrementalAuthorizationRequest}; use async_trait::async_trait; use common_utils::errors::CustomResult; use diesel_models::authorization::AuthorizationNew; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{ self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails, PaymentAddress, }, utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "incremental_authorization")] pub struct PaymentIncrementalAuthorization; type PaymentIncrementalAuthorizationOperation<'b, F> = BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[enums::IntentStatus::RequiresCapture], "increment authorization", )?; if payment_intent.incremental_authorization_allowed != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot increment authorization this payment because it is not allowed for incremental_authorization".to_owned(), })? } let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization) // request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount if payment_attempt.get_total_amount() > request.amount { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than original authorized amount".to_owned(), })? } let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = payments::PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount: amount.into(), email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: PaymentAddress::new(None, None, None, None), confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: Some(IncrementalAuthorizationDetails { additional_amount: request.amount - amount, total_amount: request.amount, reason: request.reason.clone(), authorization_id: None, }), authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, payments::PaymentData<F>, )> where F: 'b + Send, { let new_authorization_count = payment_data .payment_intent .authorization_count .map(|count| count + 1) .unwrap_or(1); // Create new authorization record let authorization_new = AuthorizationNew { authorization_id: format!( "{}_{}", common_utils::generate_id_with_default_len("auth"), new_authorization_count ), merchant_id: payment_data.payment_intent.merchant_id.clone(), payment_id: payment_data.payment_intent.payment_id.clone(), amount: payment_data .incremental_authorization_details .clone() .map(|details| details.total_amount) .ok_or( report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "missing incremental_authorization_details in payment_data", ), )?, status: common_enums::AuthorizationStatus::Processing, error_code: None, error_message: None, connector_authorization_id: None, previously_authorized_amount: payment_data.payment_attempt.get_total_amount(), }; let authorization = state .store .insert_authorization(authorization_new.clone()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Authorization with authorization_id {} already exists", authorization_new.authorization_id ), }) .attach_printable("failed while inserting new authorization")?; // Update authorization_count in payment_intent payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count: new_authorization_count, }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to update authorization_count in Payment Intent")?; match &payment_data.incremental_authorization_details { Some(details) => { payment_data.incremental_authorization_details = Some(IncrementalAuthorizationDetails { authorization_id: Some(authorization.authorization_id), ..details.clone() }); } None => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data")?, } Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, operations::ValidateResult, )> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut payments::PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut payments::PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &PaymentsIncrementalAuthorizationRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut payments::PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsIncrementalAuthorizationRequest}; use async_trait::async_trait; use common_utils::errors::CustomResult; use diesel_models::authorization::AuthorizationNew; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{ self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails, PaymentAddress, }, utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "incremental_authorization")] pub struct PaymentIncrementalAuthorization; type PaymentIncrementalAuthorizationOperation<'b, F> = BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[enums::IntentStatus::RequiresCapture], "increment authorization", )?; if payment_intent.incremental_authorization_allowed != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot increment authorization this payment because it is not allowed for incremental_authorization".to_owned(), })? } let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization) // request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount if payment_attempt.get_total_amount() > request.amount { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than original authorized amount".to_owned(), })? } let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = payments::PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount: amount.into(), email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: PaymentAddress::new(None, None, None, None), confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: Some(IncrementalAuthorizationDetails { additional_amount: request.amount - amount, total_amount: request.amount, reason: request.reason.clone(), authorization_id: None, }), authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, payments::PaymentData<F>, )> where F: 'b + Send, { let new_authorization_count = payment_data .payment_intent .authorization_count .map(|count| count + 1) .unwrap_or(1); // Create new authorization record let authorization_new = AuthorizationNew { authorization_id: format!( "{}_{}", common_utils::generate_id_with_default_len("auth"), new_authorization_count ), merchant_id: payment_data.payment_intent.merchant_id.clone(), payment_id: payment_data.payment_intent.payment_id.clone(), amount: payment_data .incremental_authorization_details .clone() .map(|details| details.total_amount) .ok_or( report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "missing incremental_authorization_details in payment_data", ), )?, status: common_enums::AuthorizationStatus::Processing, error_code: None, error_message: None, connector_authorization_id: None, previously_authorized_amount: payment_data.payment_attempt.get_total_amount(), }; let authorization = state .store .insert_authorization(authorization_new.clone()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Authorization with authorization_id {} already exists", authorization_new.authorization_id ), }) .attach_printable("failed while inserting new authorization")?; // Update authorization_count in payment_intent payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count: new_authorization_count, }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to update authorization_count in Payment Intent")?; match &payment_data.incremental_authorization_details { Some(details) => { payment_data.incremental_authorization_details = Some(IncrementalAuthorizationDetails { authorization_id: Some(authorization.authorization_id), ..details.clone() }); } None => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data")?, } Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, operations::ValidateResult, )> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut payments::PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut payments::PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &PaymentsIncrementalAuthorizationRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut payments::PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsIncrementalAuthorizationRequest}; use async_trait::async_trait; use common_utils::errors::CustomResult; use diesel_models::authorization::AuthorizationNew; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{ self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails, PaymentAddress, }, utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "incremental_authorization")] pub struct PaymentIncrementalAuthorization; type PaymentIncrementalAuthorizationOperation<'b, F> = BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[enums::IntentStatus::RequiresCapture], "increment authorization", )?; if payment_intent.incremental_authorization_allowed != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot increment authorization this payment because it is not allowed for incremental_authorization".to_owned(), })? } let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization) // request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount if payment_attempt.get_total_amount() > request.amount { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than original authorized amount".to_owned(), })? } let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = payments::PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount: amount.into(), email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: PaymentAddress::new(None, None, None, None), confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: Some(IncrementalAuthorizationDetails { additional_amount: request.amount - amount, total_amount: request.amount, reason: request.reason.clone(), authorization_id: None, }), authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, payments::PaymentData<F>, )> where F: 'b + Send, { let new_authorization_count = payment_data .payment_intent .authorization_count .map(|count| count + 1) .unwrap_or(1); // Create new authorization record let authorization_new = AuthorizationNew { authorization_id: format!( "{}_{}", common_utils::generate_id_with_default_len("auth"), new_authorization_count ), merchant_id: payment_data.payment_intent.merchant_id.clone(), payment_id: payment_data.payment_intent.payment_id.clone(), amount: payment_data .incremental_authorization_details .clone() .map(|details| details.total_amount) .ok_or( report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "missing incremental_authorization_details in payment_data", ), )?, status: common_enums::AuthorizationStatus::Processing, error_code: None, error_message: None, connector_authorization_id: None, previously_authorized_amount: payment_data.payment_attempt.get_total_amount(), }; let authorization = state .store .insert_authorization(authorization_new.clone()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Authorization with authorization_id {} already exists", authorization_new.authorization_id ), }) .attach_printable("failed while inserting new authorization")?; // Update authorization_count in payment_intent payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count: new_authorization_count, }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to update authorization_count in Payment Intent")?; match &payment_data.incremental_authorization_details { Some(details) => { payment_data.incremental_authorization_details = Some(IncrementalAuthorizationDetails { authorization_id: Some(authorization.authorization_id), ..details.clone() }); } None => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data")?, } Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, operations::ValidateResult, )> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut payments::PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut payments::PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &PaymentsIncrementalAuthorizationRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut payments::PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsIncrementalAuthorizationRequest}; use async_trait::async_trait; use common_utils::errors::CustomResult; use diesel_models::authorization::AuthorizationNew; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{ self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails, PaymentAddress, }, utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "incremental_authorization")] pub struct PaymentIncrementalAuthorization; type PaymentIncrementalAuthorizationOperation<'b, F> = BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[enums::IntentStatus::RequiresCapture], "increment authorization", )?; if payment_intent.incremental_authorization_allowed != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot increment authorization this payment because it is not allowed for incremental_authorization".to_owned(), })? } let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization) // request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount if payment_attempt.get_total_amount() > request.amount { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than original authorized amount".to_owned(), })? } let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = payments::PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount: amount.into(), email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: PaymentAddress::new(None, None, None, None), confirm: None, payment_method_data: None, payment_method_info: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: Some(IncrementalAuthorizationDetails { additional_amount: request.amount - amount, total_amount: request.amount, reason: request.reason.clone(), authorization_id: None, }), authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, payments::PaymentData<F>, )> where F: 'b + Send, { let new_authorization_count = payment_data .payment_intent .authorization_count .map(|count| count + 1) .unwrap_or(1); // Create new authorization record let authorization_new = AuthorizationNew { authorization_id: format!( "{}_{}", common_utils::generate_id_with_default_len("auth"), new_authorization_count ), merchant_id: payment_data.payment_intent.merchant_id.clone(), payment_id: payment_data.payment_intent.payment_id.clone(), amount: payment_data .incremental_authorization_details .clone() .map(|details| details.total_amount) .ok_or( report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "missing incremental_authorization_details in payment_data", ), )?, status: common_enums::AuthorizationStatus::Processing, error_code: None, error_message: None, connector_authorization_id: None, previously_authorized_amount: payment_data.payment_attempt.get_total_amount(), }; let authorization = state .store .insert_authorization(authorization_new.clone()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Authorization with authorization_id {} already exists", authorization_new.authorization_id ), }) .attach_printable("failed while inserting new authorization")?; // Update authorization_count in payment_intent payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count: new_authorization_count, }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to update authorization_count in Payment Intent")?; match &payment_data.incremental_authorization_details { Some(details) => { payment_data.incremental_authorization_details = Some(IncrementalAuthorizationDetails { authorization_id: Some(authorization.authorization_id), ..details.clone() }); } None => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data")?, } Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsIncrementalAuthorizationRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, operations::ValidateResult, )> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut payments::PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut payments::PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &PaymentsIncrementalAuthorizationRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut payments::PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentIncrementalAuthorization; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentIncrementalAuthorization; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentIncrementalAuthorization; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payments_incremental_authorization.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentIncrementalAuthorization; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/tax_calculation.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentSessionUpdate; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/tax_calculation.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentSessionUpdate; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/tax_calculation.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentSessionUpdate; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/tax_calculation.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentSessionUpdate; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations, types as payment_types, CustomerDetails, PaymentAddress, PaymentData, }, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "sync")] pub struct PaymentStatus; type PaymentStatusOperation<'b, F, R> = BoxedOperation<'b, F, R, PaymentData<F>>; impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for &PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(*self) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::Customer>, ), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, state: &'a SessionState, payment_attempt: &storage::PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue, schedule_time).await } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, _key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { get_tracker_for_sync( payment_id, merchant_account, key_store, state, request, self, merchant_account.storage_scheme, platform_merchant_account, ) .await } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( _payment_id: &api::PaymentIdType, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _state: &SessionState, _request: &api::PaymentsRetrieveRequest, _operation: Op, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { todo!() } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( payment_id: &api::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( state, payment_id, merchant_account.get_id(), key_store, storage_scheme, platform_merchant_account, ) .await?; helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; let payment_id = payment_attempt.payment_id.clone(); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; payment_attempt.encoded_data.clone_from(&request.param); let db = &*state.store; let key_manager_state = &state.into(); let attempts = match request.expand_attempts { Some(true) => { Some(db .find_attempts_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_account.get_id()) })?) }, _ => None, }; let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) { let captures = db .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &payment_attempt.merchant_id, &payment_attempt.payment_id, &payment_attempt.attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; Some(payment_types::MultipleCaptureData::new_for_sync( captures, request.expand_captures, )?) } else { None }; let refunds = db .find_refund_by_payment_id_merchant_id( &payment_id, merchant_account.get_id(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let authorizations = db .find_all_authorizations_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let disputes = db .find_disputes_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) }) .ok() } else { None }; let contains_encoded_data = payment_attempt.encoded_data.is_some(); let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_account.get_id(), mcd) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_info = if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { match db .find_payment_method( &(state.into()), key_store, payment_method_id, storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db")? } } } } else { None }; let merchant_id = payment_intent.merchant_id.clone(); let authentication = payment_attempt.authentication_id.clone().async_map(|authentication_id| async move { db.find_authentication_by_merchant_id_authentication_id( &merchant_id, authentication_id.clone(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}")) }).await .transpose()?; let payment_link_data = payment_intent .payment_link_id .as_ref() .async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id)) .await .transpose()?; let payment_data = PaymentData { flow: PhantomData, payment_intent, currency, amount, email: None, mandate_id: payment_attempt .mandate_id .clone() .map(|id| api_models::payments::MandateIds { mandate_id: Some(id), mandate_reference_id: None, }), mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: Some(request.force_sync), payment_method_data: None, payment_method_info, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), payment_attempt, refunds, disputes, attempts, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data, redirect_response: None, payment_link_data, surcharge_details: None, frm_message: frm_response, incremental_authorization_details: None, authorizations, authentication, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(operation), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRetrieveRequest, PaymentData<F>> for PaymentStatus { fn validate_request<'b>( &'b self, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, operations::ValidateResult, )> { let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: request.resource_id.clone(), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } pub async fn get_payment_intent_payment_attempt( state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, id, merchant_id, key_store, storage_scheme, ) .await?; pa = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, pi.active_attempt.get_id().as_str(), storage_scheme, ) .await?; } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { pa = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { pa = db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PreprocessingId(ref id) => { pa = db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } } error_stack::Result::<_, errors::StorageError>::Ok((pi, pa)) }; get_pi_pa() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) // TODO (#7195): Add platform merchant account validation once client_secret auth is solved } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations, types as payment_types, CustomerDetails, PaymentAddress, PaymentData, }, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "sync")] pub struct PaymentStatus; type PaymentStatusOperation<'b, F, R> = BoxedOperation<'b, F, R, PaymentData<F>>; impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for &PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(*self) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::Customer>, ), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, state: &'a SessionState, payment_attempt: &storage::PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue, schedule_time).await } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, _key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { get_tracker_for_sync( payment_id, merchant_account, key_store, state, request, self, merchant_account.storage_scheme, platform_merchant_account, ) .await } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( _payment_id: &api::PaymentIdType, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _state: &SessionState, _request: &api::PaymentsRetrieveRequest, _operation: Op, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { todo!() } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( payment_id: &api::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( state, payment_id, merchant_account.get_id(), key_store, storage_scheme, platform_merchant_account, ) .await?; helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; let payment_id = payment_attempt.payment_id.clone(); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; payment_attempt.encoded_data.clone_from(&request.param); let db = &*state.store; let key_manager_state = &state.into(); let attempts = match request.expand_attempts { Some(true) => { Some(db .find_attempts_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_account.get_id()) })?) }, _ => None, }; let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) { let captures = db .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &payment_attempt.merchant_id, &payment_attempt.payment_id, &payment_attempt.attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; Some(payment_types::MultipleCaptureData::new_for_sync( captures, request.expand_captures, )?) } else { None }; let refunds = db .find_refund_by_payment_id_merchant_id( &payment_id, merchant_account.get_id(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let authorizations = db .find_all_authorizations_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let disputes = db .find_disputes_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) }) .ok() } else { None }; let contains_encoded_data = payment_attempt.encoded_data.is_some(); let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_account.get_id(), mcd) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_info = if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { match db .find_payment_method( &(state.into()), key_store, payment_method_id, storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db")? } } } } else { None }; let merchant_id = payment_intent.merchant_id.clone(); let authentication = payment_attempt.authentication_id.clone().async_map(|authentication_id| async move { db.find_authentication_by_merchant_id_authentication_id( &merchant_id, authentication_id.clone(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}")) }).await .transpose()?; let payment_link_data = payment_intent .payment_link_id .as_ref() .async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id)) .await .transpose()?; let payment_data = PaymentData { flow: PhantomData, payment_intent, currency, amount, email: None, mandate_id: payment_attempt .mandate_id .clone() .map(|id| api_models::payments::MandateIds { mandate_id: Some(id), mandate_reference_id: None, }), mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: Some(request.force_sync), payment_method_data: None, payment_method_info, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), payment_attempt, refunds, disputes, attempts, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data, redirect_response: None, payment_link_data, surcharge_details: None, frm_message: frm_response, incremental_authorization_details: None, authorizations, authentication, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(operation), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRetrieveRequest, PaymentData<F>> for PaymentStatus { fn validate_request<'b>( &'b self, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, operations::ValidateResult, )> { let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: request.resource_id.clone(), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } pub async fn get_payment_intent_payment_attempt( state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, id, merchant_id, key_store, storage_scheme, ) .await?; pa = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, pi.active_attempt.get_id().as_str(), storage_scheme, ) .await?; } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { pa = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { pa = db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PreprocessingId(ref id) => { pa = db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } } error_stack::Result::<_, errors::StorageError>::Ok((pi, pa)) }; get_pi_pa() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) // TODO (#7195): Add platform merchant account validation once client_secret auth is solved } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations, types as payment_types, CustomerDetails, PaymentAddress, PaymentData, }, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "sync")] pub struct PaymentStatus; type PaymentStatusOperation<'b, F, R> = BoxedOperation<'b, F, R, PaymentData<F>>; impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for &PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(*self) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::Customer>, ), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, state: &'a SessionState, payment_attempt: &storage::PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue, schedule_time).await } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, _key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { get_tracker_for_sync( payment_id, merchant_account, key_store, state, request, self, merchant_account.storage_scheme, platform_merchant_account, ) .await } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( _payment_id: &api::PaymentIdType, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _state: &SessionState, _request: &api::PaymentsRetrieveRequest, _operation: Op, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { todo!() } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( payment_id: &api::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( state, payment_id, merchant_account.get_id(), key_store, storage_scheme, platform_merchant_account, ) .await?; helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; let payment_id = payment_attempt.payment_id.clone(); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; payment_attempt.encoded_data.clone_from(&request.param); let db = &*state.store; let key_manager_state = &state.into(); let attempts = match request.expand_attempts { Some(true) => { Some(db .find_attempts_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_account.get_id()) })?) }, _ => None, }; let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) { let captures = db .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &payment_attempt.merchant_id, &payment_attempt.payment_id, &payment_attempt.attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; Some(payment_types::MultipleCaptureData::new_for_sync( captures, request.expand_captures, )?) } else { None }; let refunds = db .find_refund_by_payment_id_merchant_id( &payment_id, merchant_account.get_id(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let authorizations = db .find_all_authorizations_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let disputes = db .find_disputes_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) }) .ok() } else { None }; let contains_encoded_data = payment_attempt.encoded_data.is_some(); let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_account.get_id(), mcd) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_info = if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { match db .find_payment_method( &(state.into()), key_store, payment_method_id, storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db")? } } } } else { None }; let merchant_id = payment_intent.merchant_id.clone(); let authentication = payment_attempt.authentication_id.clone().async_map(|authentication_id| async move { db.find_authentication_by_merchant_id_authentication_id( &merchant_id, authentication_id.clone(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}")) }).await .transpose()?; let payment_link_data = payment_intent .payment_link_id .as_ref() .async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id)) .await .transpose()?; let payment_data = PaymentData { flow: PhantomData, payment_intent, currency, amount, email: None, mandate_id: payment_attempt .mandate_id .clone() .map(|id| api_models::payments::MandateIds { mandate_id: Some(id), mandate_reference_id: None, }), mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: Some(request.force_sync), payment_method_data: None, payment_method_info, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), payment_attempt, refunds, disputes, attempts, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data, redirect_response: None, payment_link_data, surcharge_details: None, frm_message: frm_response, incremental_authorization_details: None, authorizations, authentication, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(operation), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRetrieveRequest, PaymentData<F>> for PaymentStatus { fn validate_request<'b>( &'b self, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, operations::ValidateResult, )> { let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: request.resource_id.clone(), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } pub async fn get_payment_intent_payment_attempt( state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, id, merchant_id, key_store, storage_scheme, ) .await?; pa = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, pi.active_attempt.get_id().as_str(), storage_scheme, ) .await?; } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { pa = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { pa = db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PreprocessingId(ref id) => { pa = db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } } error_stack::Result::<_, errors::StorageError>::Ok((pi, pa)) }; get_pi_pa() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) // TODO (#7195): Add platform merchant account validation once client_secret auth is solved } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations, types as payment_types, CustomerDetails, PaymentAddress, PaymentData, }, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "sync")] pub struct PaymentStatus; type PaymentStatusOperation<'b, F, R> = BoxedOperation<'b, F, R, PaymentData<F>>; impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for &PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(*self) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::Customer>, ), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, state: &'a SessionState, payment_attempt: &storage::PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue, schedule_time).await } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, _key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { get_tracker_for_sync( payment_id, merchant_account, key_store, state, request, self, merchant_account.storage_scheme, platform_merchant_account, ) .await } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( _payment_id: &api::PaymentIdType, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _state: &SessionState, _request: &api::PaymentsRetrieveRequest, _operation: Op, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { todo!() } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( payment_id: &api::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( state, payment_id, merchant_account.get_id(), key_store, storage_scheme, platform_merchant_account, ) .await?; helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; let payment_id = payment_attempt.payment_id.clone(); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; payment_attempt.encoded_data.clone_from(&request.param); let db = &*state.store; let key_manager_state = &state.into(); let attempts = match request.expand_attempts { Some(true) => { Some(db .find_attempts_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_account.get_id()) })?) }, _ => None, }; let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) { let captures = db .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &payment_attempt.merchant_id, &payment_attempt.payment_id, &payment_attempt.attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; Some(payment_types::MultipleCaptureData::new_for_sync( captures, request.expand_captures, )?) } else { None }; let refunds = db .find_refund_by_payment_id_merchant_id( &payment_id, merchant_account.get_id(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let authorizations = db .find_all_authorizations_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_account.get_id() ) })?; let disputes = db .find_disputes_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) }) .ok() } else { None }; let contains_encoded_data = payment_attempt.encoded_data.is_some(); let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_account.get_id(), mcd) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_info = if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { match db .find_payment_method( &(state.into()), key_store, payment_method_id, storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db")? } } } } else { None }; let merchant_id = payment_intent.merchant_id.clone(); let authentication = payment_attempt.authentication_id.clone().async_map(|authentication_id| async move { db.find_authentication_by_merchant_id_authentication_id( &merchant_id, authentication_id.clone(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}")) }).await .transpose()?; let payment_link_data = payment_intent .payment_link_id .as_ref() .async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id)) .await .transpose()?; let payment_data = PaymentData { flow: PhantomData, payment_intent, currency, amount, email: None, mandate_id: payment_attempt .mandate_id .clone() .map(|id| api_models::payments::MandateIds { mandate_id: Some(id), mandate_reference_id: None, }), mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: Some(request.force_sync), payment_method_data: None, payment_method_info, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), payment_attempt, refunds, disputes, attempts, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data, redirect_response: None, payment_link_data, surcharge_details: None, frm_message: frm_response, incremental_authorization_details: None, authorizations, authentication, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(operation), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRetrieveRequest, PaymentData<F>> for PaymentStatus { fn validate_request<'b>( &'b self, request: &api::PaymentsRetrieveRequest, merchant_account: &domain::MerchantAccount, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, operations::ValidateResult, )> { let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_account.get_id().to_owned(), payment_id: request.resource_id.clone(), storage_scheme: merchant_account.storage_scheme, requeue: false, }, )) } } pub async fn get_payment_intent_payment_attempt( state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, id, merchant_id, key_store, storage_scheme, ) .await?; pa = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, pi.active_attempt.get_id().as_str(), storage_scheme, ) .await?; } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { pa = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { pa = db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PreprocessingId(ref id) => { pa = db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } } error_stack::Result::<_, errors::StorageError>::Ok((pi, pa)) }; get_pi_pa() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) // TODO (#7195): Add platform merchant account validation once client_secret auth is solved } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentStatus; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentStatus; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentStatus; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_status.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentStatus; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentReject; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentReject; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=PaymentOperation roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct PaymentReject; <|fim_suffix|> <|fim_middle|> <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_reject.rs" crate="router" role="use_site"> <|fim_prefix|> pub struct PaymentReject; <|fim_suffix|> <|fim_middle|>
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/routes/dummy_connector/errors.rs" crate="router" role="use_site"> #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum ErrorType { ServerNotAvailable, ObjectNotFound, InvalidRequestError, } #[derive(Debug, Clone, router_derive::ApiError)] #[error(error_type_enum = ErrorType)] // TODO: Remove this line if InternalServerError is used anywhere #[allow(dead_code)] pub enum DummyConnectorErrors { #[error(error_type = ErrorType::ServerNotAvailable, code = "DC_00", message = "Something went wrong")] InternalServerError, #[error(error_type = ErrorType::ObjectNotFound, code = "DC_01", message = "Payment does not exist in our records")] PaymentNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_02", message = "Missing required param: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_03", message = "The refund amount exceeds the amount captured")] RefundAmountExceedsPaymentAmount, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_04", message = "Card not supported. Please use test cards")] CardNotSupported, #[error(error_type = ErrorType::ObjectNotFound, code = "DC_05", message = "Refund does not exist in our records")] RefundNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_06", message = "Payment is not successful")] PaymentNotSuccessful, #[error(error_type = ErrorType::ServerNotAvailable, code = "DC_07", message = "Error occurred while storing the payment")] PaymentStoringError, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_08", message = "Payment declined: {message}")] PaymentDeclined { message: &'static str }, } impl core::fmt::Display for DummyConnectorErrors { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, r#"{{"error":{}}}"#, serde_json::to_string(self) .unwrap_or_else(|_| "Dummy connector error response".to_string()) ) } } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for DummyConnectorErrors { fn switch(&self) -> api_models::errors::types::ApiErrorResponse { use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; match self { Self::InternalServerError => { AER::InternalServerError(ApiError::new("DC", 0, self.error_message(), None)) } Self::PaymentNotFound => { AER::NotFound(ApiError::new("DC", 1, self.error_message(), None)) } Self::MissingRequiredField { field_name: _ } => { AER::BadRequest(ApiError::new("DC", 2, self.error_message(), None)) } Self::RefundAmountExceedsPaymentAmount => { AER::InternalServerError(ApiError::new("DC", 3, self.error_message(), None)) } Self::CardNotSupported => { AER::BadRequest(ApiError::new("DC", 4, self.error_message(), None)) } Self::RefundNotFound => { AER::NotFound(ApiError::new("DC", 5, self.error_message(), None)) } Self::PaymentNotSuccessful => { AER::BadRequest(ApiError::new("DC", 6, self.error_message(), None)) } Self::PaymentStoringError => { AER::InternalServerError(ApiError::new("DC", 7, self.error_message(), None)) } Self::PaymentDeclined { message: _ } => { AER::BadRequest(ApiError::new("DC", 8, self.error_message(), None)) } } } } <file_sep path="hyperswitch/crates/router/src/routes/dummy_connector/errors.rs" crate="router" role="use_site"> #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum ErrorType { ServerNotAvailable, ObjectNotFound, InvalidRequestError, } #[derive(Debug, Clone, router_derive::ApiError)] #[error(error_type_enum = ErrorType)] // TODO: Remove this line if InternalServerError is used anywhere #[allow(dead_code)] pub enum DummyConnectorErrors { #[error(error_type = ErrorType::ServerNotAvailable, code = "DC_00", message = "Something went wrong")] InternalServerError, #[error(error_type = ErrorType::ObjectNotFound, code = "DC_01", message = "Payment does not exist in our records")] PaymentNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_02", message = "Missing required param: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_03", message = "The refund amount exceeds the amount captured")] RefundAmountExceedsPaymentAmount, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_04", message = "Card not supported. Please use test cards")] CardNotSupported, #[error(error_type = ErrorType::ObjectNotFound, code = "DC_05", message = "Refund does not exist in our records")] RefundNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_06", message = "Payment is not successful")] PaymentNotSuccessful, #[error(error_type = ErrorType::ServerNotAvailable, code = "DC_07", message = "Error occurred while storing the payment")] PaymentStoringError, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_08", message = "Payment declined: {message}")] PaymentDeclined { message: &'static str }, } impl core::fmt::Display for DummyConnectorErrors { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, r#"{{"error":{}}}"#, serde_json::to_string(self) .unwrap_or_else(|_| "Dummy connector error response".to_string()) ) } } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for DummyConnectorErrors { fn switch(&self) -> api_models::errors::types::ApiErrorResponse { use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; match self { Self::InternalServerError => { AER::InternalServerError(ApiError::new("DC", 0, self.error_message(), None)) } Self::PaymentNotFound => { AER::NotFound(ApiError::new("DC", 1, self.error_message(), None)) } Self::MissingRequiredField { field_name: _ } => { AER::BadRequest(ApiError::new("DC", 2, self.error_message(), None)) } Self::RefundAmountExceedsPaymentAmount => { AER::InternalServerError(ApiError::new("DC", 3, self.error_message(), None)) } Self::CardNotSupported => { AER::BadRequest(ApiError::new("DC", 4, self.error_message(), None)) } Self::RefundNotFound => { AER::NotFound(ApiError::new("DC", 5, self.error_message(), None)) } Self::PaymentNotSuccessful => { AER::BadRequest(ApiError::new("DC", 6, self.error_message(), None)) } Self::PaymentStoringError => { AER::InternalServerError(ApiError::new("DC", 7, self.error_message(), None)) } Self::PaymentDeclined { message: _ } => { AER::BadRequest(ApiError::new("DC", 8, self.error_message(), None)) } } } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=ApiError roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=ApiError roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/errors.rs" crate="router" role="use_site"> use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response as errors; use crate::core::errors::CustomersErrorResponse; #[derive(Debug, router_derive::ApiError, Clone)] #[error(error_type_enum = StripeErrorType)] pub enum StripeErrorCode { /* "error": { "message": "Invalid API Key provided: sk_jkjgs****nlgs", "type": "invalid_request_error" } */ #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_01", message = "Invalid API Key provided" )] Unauthorized, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")] InvalidRequestUrl, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")] ParameterMissing { field_name: String, param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown", message = "{field_name} contains invalid data. Expected format is {expected_format}." )] ParameterUnknown { field_name: String, expected_format: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")] RefundAmountExceedsPaymentAmount { param: String }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")] PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")] PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")] DisputeFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")] ExpiredCard, #[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")] InvalidCardType, #[error( error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")] RefundFailed, // stripe error code #[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")] PayoutFailed, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] InternalServerError, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] DuplicateRefundRequest, #[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")] MandateActive, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")] CustomerRedacted, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")] DuplicateCustomer, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")] RefundNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")] ClientSecretNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")] CustomerNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")] ConfigNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")] DuplicateConfig, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")] PaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")] PaymentMethodNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")] MerchantAccountNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")] ResourceIdNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")] MerchantConnectorAccountNotFound { id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")] MerchantConnectorAccountDisabled, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")] ApiKeyNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")] PayoutNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")] EventNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")] DuplicatePayout { payout_id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")] ReturnUrlUnavailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")] DuplicateMerchantAccount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")] DuplicateMerchantConnectorAccount { profile_id: String, connector_label: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")] DuplicatePaymentMethod, #[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")] SerdeQsError { error_message: String, param: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")] PaymentIntentInvalidParameter { param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_05", message = "{message}" )] InvalidRequestData { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_10", message = "{message}" )] PreconditionFailed { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment has not succeeded yet" )] PaymentFailed, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The verification did not succeeded" )] VerificationFailed { data: Option<serde_json::Value> }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "Reached maximum refund attempts" )] MaximumRefundCount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")] DuplicateMandate, #[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")] AddressNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")] PaymentIntentUnexpectedState { current_flow: String, field_name: String, current_value: String, states: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")] PaymentIntentMandateInvalid { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")] DuplicatePayment { payment_id: common_utils::id_type::PaymentId, }, #[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")] ExternalConnectorError { code: String, message: String, connector: String, status_code: u16, }, #[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")] PaymentBlockedError { code: u16, message: String, status: String, reason: String, }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")] IncorrectConnectorNameGiven, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")] ResourceMissing { object: String, id: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")] FileValidationFailed, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")] MissingFile, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")] MissingFilePurpose, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")] MissingFileContentType, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")] FileNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")] FileNotAvailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")] FileProviderNotSupported, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")] WebhookProcessingError, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")] PaymentMethodUnactivated, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")] HyperswitchUnprocessableEntity { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")] LockTimeout, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")] InvalidTenant, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")] PlatformBadRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")] PlatformUnauthorizedRequest, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes /* AccountCountryInvalidAddress, AccountErrorCountryChangeRequiresAdditionalSteps, AccountInformationMismatch, AccountInvalid, AccountNumberInvalid, AcssDebitSessionIncomplete, AlipayUpgradeRequired, AmountTooLarge, AmountTooSmall, ApiKeyExpired, AuthenticationRequired, BalanceInsufficient, BankAccountBadRoutingNumbers, BankAccountDeclined, BankAccountExists, BankAccountUnusable, BankAccountUnverified, BankAccountVerificationFailed, BillingInvalidMandate, BitcoinUpgradeRequired, CardDeclineRateLimitExceeded, CardDeclined, CardholderPhoneNumberRequired, ChargeAlreadyCaptured, ChargeAlreadyRefunded, ChargeDisputed, ChargeExceedsSourceLimit, ChargeExpiredForCapture, ChargeInvalidParameter, ClearingCodeUnsupported, CountryCodeInvalid, CountryUnsupported, CouponExpired, CustomerMaxPaymentMethods, CustomerMaxSubscriptions, DebitNotAuthorized, EmailInvalid, ExpiredCard, IdempotencyKeyInUse, IncorrectAddress, IncorrectCvc, IncorrectNumber, IncorrectZip, InstantPayoutsConfigDisabled, InstantPayoutsCurrencyDisabled, InstantPayoutsLimitExceeded, InstantPayoutsUnsupported, InsufficientFunds, IntentInvalidState, IntentVerificationMethodMissing, InvalidCardType, InvalidCharacters, InvalidChargeAmount, InvalidCvc, InvalidExpiryMonth, InvalidExpiryYear, InvalidNumber, InvalidSourceUsage, InvoiceNoCustomerLineItems, InvoiceNoPaymentMethodTypes, InvoiceNoSubscriptionLineItems, InvoiceNotEditable, InvoiceOnBehalfOfNotEditable, InvoicePaymentIntentRequiresAction, InvoiceUpcomingNone, LivemodeMismatch, LockTimeout, Missing, NoAccount, NotAllowedOnStandardAccount, OutOfInventory, ParameterInvalidEmpty, ParameterInvalidInteger, ParameterInvalidStringBlank, ParameterInvalidStringEmpty, ParametersExclusive, PaymentIntentActionRequired, PaymentIntentIncompatiblePaymentMethod, PaymentIntentInvalidParameter, PaymentIntentKonbiniRejectedConfirmationNumber, PaymentIntentPaymentAttemptExpired, PaymentIntentUnexpectedState, PaymentMethodBankAccountAlreadyVerified, PaymentMethodBankAccountBlocked, PaymentMethodBillingDetailsAddressMissing, PaymentMethodCurrencyMismatch, PaymentMethodInvalidParameter, PaymentMethodInvalidParameterTestmode, PaymentMethodMicrodepositFailed, PaymentMethodMicrodepositVerificationAmountsInvalid, PaymentMethodMicrodepositVerificationAmountsMismatch, PaymentMethodMicrodepositVerificationAttemptsExceeded, PaymentMethodMicrodepositVerificationDescriptorCodeMismatch, PaymentMethodMicrodepositVerificationTimeout, PaymentMethodProviderDecline, PaymentMethodProviderTimeout, PaymentMethodUnexpectedState, PaymentMethodUnsupportedType, PayoutsNotAllowed, PlatformAccountRequired, PlatformApiKeyExpired, PostalCodeInvalid, ProcessingError, ProductInactive, RateLimit, ReferToCustomer, RefundDisputedPayment, ResourceAlreadyExists, ResourceMissing, ReturnIntentAlreadyProcessed, RoutingNumberInvalid, SecretKeyRequired, SepaUnsupportedAccount, SetupAttemptFailed, SetupIntentAuthenticationFailure, SetupIntentInvalidParameter, SetupIntentSetupAttemptExpired, SetupIntentUnexpectedState, ShippingCalculationFailed, SkuInactive, StateUnsupported, StatusTransitionInvalid, TaxIdInvalid, TaxesCalculationFailed, TerminalLocationCountryUnsupported, TestmodeChargesOnly, TlsVersionUnsupported, TokenInUse, TransferSourceBalanceParametersMismatch, TransfersNotAllowed, */ } impl ::core::fmt::Display for StripeErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{{\"error\": {}}}", serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string()) ) } } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] #[allow(clippy::enum_variant_names)] pub enum StripeErrorType { ApiError, CardError, InvalidRequestError, ConnectorError, HyperswitchError, } impl From<errors::ApiErrorResponse> for StripeErrorCode { fn from(value: errors::ApiErrorResponse) -> Self { match value { errors::ApiErrorResponse::Unauthorized | errors::ApiErrorResponse::InvalidJwtToken | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie | errors::ApiErrorResponse::InvalidEphemeralKey | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin | errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl, errors::ApiErrorResponse::MissingRequiredField { field_name } => { Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), } } errors::ApiErrorResponse::UnprocessableEntity { message } => { Self::HyperswitchUnprocessableEntity { message } } errors::ApiErrorResponse::MissingRequiredFields { field_names } => { // Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String Self::ParameterMissing { field_name: field_names.clone().join(", "), param: field_names.clone().join(", "), } } errors::ApiErrorResponse::GenericNotFoundError { message } => { Self::GenericNotFoundError { message } } errors::ApiErrorResponse::GenericDuplicateError { message } => { Self::GenericDuplicateError { message } } // parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff errors::ApiErrorResponse::InvalidDataFormat { field_name, expected_format, } => Self::ParameterUnknown { field_name, expected_format, }, errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => { Self::RefundAmountExceedsPaymentAmount { param: "amount".to_owned(), } } errors::ApiErrorResponse::PaymentAuthorizationFailed { data } | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => { Self::PaymentIntentAuthenticationFailure { data } } errors::ApiErrorResponse::VerificationFailed { data } => { Self::VerificationFailed { data } } errors::ApiErrorResponse::PaymentCaptureFailed { data } => { Self::PaymentIntentPaymentAttemptFailed { data } } errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data }, errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard, errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed, errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed, errors::ApiErrorResponse::MandateUpdateFailed | errors::ApiErrorResponse::MandateSerializationFailed | errors::ApiErrorResponse::MandateDeserializationFailed | errors::ApiErrorResponse::InternalServerError | errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code errors::ApiErrorResponse::ExternalConnectorError { code, message, connector, status_code, .. } => Self::ExternalConnectorError { code, message, connector, status_code, }, errors::ApiErrorResponse::IncorrectConnectorNameGiven => { Self::IncorrectConnectorNameGiven } errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest, errors::ApiErrorResponse::DuplicatePayout { payout_id } => { Self::DuplicatePayout { payout_id } } errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound, errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound, errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound, errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound, errors::ApiErrorResponse::ClientSecretNotGiven | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => { Self::MerchantConnectorAccountNotFound { id } } errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound, errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound, errors::ApiErrorResponse::EventNotFound => Self::EventNotFound, errors::ApiErrorResponse::MandateValidationFailed { reason } => { Self::PaymentIntentMandateInvalid { message: reason } } errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable, errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount, errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id, connector_label, } => Self::DuplicateMerchantConnectorAccount { profile_id, connector_label, }, errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, errors::ApiErrorResponse::PaymentBlockedError { code, message, status, reason, } => Self::PaymentBlockedError { code, message, status, reason, }, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { param: "client_secret".to_owned(), }, errors::ApiErrorResponse::InvalidRequestData { message } => { Self::InvalidRequestData { message } } errors::ApiErrorResponse::PreconditionFailed { message } => { Self::PreconditionFailed { message } } errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), }, errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount, errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed, errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate, errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound, errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound, errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized, errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::PaymentUnexpectedState { current_flow, field_name, current_value, states, } => Self::PaymentIntentUnexpectedState { current_flow, field_name, current_value, states, }, errors::ApiErrorResponse::DuplicatePayment { payment_id } => { Self::DuplicatePayment { payment_id } } errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing { object: "dispute".to_owned(), id: dispute_id, }, errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing { object: "authentication".to_owned(), id, }, errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing { object: "business_profile".to_owned(), id, }, errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing { object: "poll".to_owned(), id, }, errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => { Self::InternalServerError } errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed, errors::ApiErrorResponse::MissingFile => Self::MissingFile, errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose, errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType, errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId, errors::ApiErrorResponse::FileNotFound => Self::FileNotFound, errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable, errors::ApiErrorResponse::MerchantConnectorAccountDisabled => { Self::MerchantConnectorAccountDisabled } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::CurrencyNotSupported { message } => { Self::CurrencyNotSupported { message } } errors::ApiErrorResponse::FileProviderNotSupported { .. } => { Self::FileProviderNotSupported } errors::ApiErrorResponse::WebhookBadRequest | errors::ApiErrorResponse::WebhookResourceNotFound | errors::ApiErrorResponse::WebhookProcessingFailure | errors::ApiErrorResponse::WebhookAuthenticationFailed | errors::ApiErrorResponse::WebhookUnprocessableEntity | errors::ApiErrorResponse::WebhookInvalidMerchantSecret => { Self::WebhookProcessingError } errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => { Self::PaymentMethodUnactivated } errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated, errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => { Self::InvalidConnectorConfiguration { config } } errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed, errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed, errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => { Self::InvalidWalletToken { wallet_name } } errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound, errors::ApiErrorResponse::LinkConfigurationError { message } => { Self::LinkConfigurationError { message } } errors::ApiErrorResponse::IntegrityCheckFailed { reason, field_names, connector_transaction_id, } => Self::IntegrityCheckFailed { reason, field_names, connector_transaction_id, }, errors::ApiErrorResponse::InvalidTenant { tenant_id: _ } | errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant, errors::ApiErrorResponse::AmountConversionFailed { amount_type } => { Self::AmountConversionFailed { amount_type } } errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest, errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest, } } } impl actix_web::ResponseError for StripeErrorCode { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; match self { Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED, Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND, Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => { StatusCode::UNPROCESSABLE_ENTITY } Self::ParameterMissing { .. } | Self::RefundAmountExceedsPaymentAmount { .. } | Self::PaymentIntentAuthenticationFailure { .. } | Self::PaymentIntentPaymentAttemptFailed { .. } | Self::ExpiredCard | Self::InvalidCardType | Self::DuplicateRefundRequest | Self::DuplicatePayout { .. } | Self::RefundNotFound | Self::CustomerNotFound | Self::ConfigNotFound | Self::DuplicateConfig | Self::ClientSecretNotFound | Self::PaymentNotFound | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound { .. } | Self::MerchantConnectorAccountDisabled | Self::MandateNotFound | Self::ApiKeyNotFound | Self::PayoutNotFound | Self::EventNotFound | Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod | Self::PaymentFailed | Self::VerificationFailed { .. } | Self::DisputeFailed { .. } | Self::MaximumRefundCount | Self::PaymentIntentInvalidParameter { .. } | Self::SerdeQsError { .. } | Self::InvalidRequestData { .. } | Self::InvalidWalletToken { .. } | Self::PreconditionFailed { .. } | Self::DuplicateMandate | Self::SuccessfulPaymentNotFound | Self::AddressNotFound | Self::ResourceIdNotFound | Self::PaymentIntentMandateInvalid { .. } | Self::PaymentIntentUnexpectedState { .. } | Self::DuplicatePayment { .. } | Self::GenericDuplicateError { .. } | Self::IncorrectConnectorNameGiven | Self::ResourceMissing { .. } | Self::FileValidationFailed | Self::MissingFile | Self::MissingFileContentType | Self::MissingFilePurpose | Self::MissingDisputeId | Self::FileNotFound | Self::FileNotAvailable | Self::FileProviderNotSupported | Self::CurrencyNotSupported { .. } | Self::DuplicateCustomer | Self::PaymentMethodUnactivated | Self::InvalidConnectorConfiguration { .. } | Self::CurrencyConversionFailed | Self::PaymentMethodDeleteFailed | Self::ExtendedCardInfoNotFound | Self::PlatformBadRequest | Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound | Self::InternalServerError | Self::MandateActive | Self::CustomerRedacted | Self::WebhookProcessingError | Self::InvalidTenant | Self::AmountConversionFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) } Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::PaymentBlockedError { code, .. } => { StatusCode::from_u16(*code).unwrap_or(StatusCode::OK) } Self::LockTimeout => StatusCode::LOCKED, } } fn error_response(&self) -> actix_web::HttpResponse { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } impl From<serde_qs::Error> for StripeErrorCode { fn from(item: serde_qs::Error) -> Self { match item { serde_qs::Error::Custom(s) => Self::SerdeQsError { error_message: s, param: None, }, serde_qs::Error::Parse(param, position) => Self::SerdeQsError { error_message: format!( "parsing failed with error: '{param}' at position: {position}" ), param: Some(param), }, serde_qs::Error::Unsupported => Self::SerdeQsError { error_message: "Given request format is not supported".to_owned(), param: None, }, serde_qs::Error::FromUtf8(_) => Self::SerdeQsError { error_message: "Failed to parse request to from utf-8".to_owned(), param: None, }, serde_qs::Error::Io(_) => Self::SerdeQsError { error_message: "Failed to parse request".to_owned(), param: None, }, serde_qs::Error::ParseInt(_) => Self::SerdeQsError { error_message: "Failed to parse integer in request".to_owned(), param: None, }, serde_qs::Error::Utf8(_) => Self::SerdeQsError { error_message: "Failed to convert utf8 to string".to_owned(), param: None, }, } } } impl ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse { fn switch(&self) -> StripeErrorCode { self.clone().into() } } impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {} impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse { fn switch(&self) -> StripeErrorCode { use StripeErrorCode as SC; match self { Self::CustomerRedacted => SC::CustomerRedacted, Self::InternalServerError => SC::InternalServerError, Self::MandateActive => SC::MandateActive, Self::CustomerNotFound => SC::CustomerNotFound, Self::CustomerAlreadyExists => SC::DuplicateCustomer, } } }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/errors.rs" crate="router" role="use_site"> use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response as errors; use crate::core::errors::CustomersErrorResponse; #[derive(Debug, router_derive::ApiError, Clone)] #[error(error_type_enum = StripeErrorType)] pub enum StripeErrorCode { /* "error": { "message": "Invalid API Key provided: sk_jkjgs****nlgs", "type": "invalid_request_error" } */ #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_01", message = "Invalid API Key provided" )] Unauthorized, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")] InvalidRequestUrl, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")] ParameterMissing { field_name: String, param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown", message = "{field_name} contains invalid data. Expected format is {expected_format}." )] ParameterUnknown { field_name: String, expected_format: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")] RefundAmountExceedsPaymentAmount { param: String }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")] PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")] PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")] DisputeFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")] ExpiredCard, #[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")] InvalidCardType, #[error( error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")] RefundFailed, // stripe error code #[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")] PayoutFailed, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] InternalServerError, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] DuplicateRefundRequest, #[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")] MandateActive, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")] CustomerRedacted, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")] DuplicateCustomer, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")] RefundNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")] ClientSecretNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")] CustomerNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")] ConfigNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")] DuplicateConfig, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")] PaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")] PaymentMethodNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")] MerchantAccountNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")] ResourceIdNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")] MerchantConnectorAccountNotFound { id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")] MerchantConnectorAccountDisabled, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")] ApiKeyNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")] PayoutNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")] EventNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")] DuplicatePayout { payout_id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")] ReturnUrlUnavailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")] DuplicateMerchantAccount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")] DuplicateMerchantConnectorAccount { profile_id: String, connector_label: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")] DuplicatePaymentMethod, #[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")] SerdeQsError { error_message: String, param: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")] PaymentIntentInvalidParameter { param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_05", message = "{message}" )] InvalidRequestData { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_10", message = "{message}" )] PreconditionFailed { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment has not succeeded yet" )] PaymentFailed, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The verification did not succeeded" )] VerificationFailed { data: Option<serde_json::Value> }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "Reached maximum refund attempts" )] MaximumRefundCount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")] DuplicateMandate, #[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")] AddressNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")] PaymentIntentUnexpectedState { current_flow: String, field_name: String, current_value: String, states: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")] PaymentIntentMandateInvalid { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")] DuplicatePayment { payment_id: common_utils::id_type::PaymentId, }, #[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")] ExternalConnectorError { code: String, message: String, connector: String, status_code: u16, }, #[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")] PaymentBlockedError { code: u16, message: String, status: String, reason: String, }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")] IncorrectConnectorNameGiven, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")] ResourceMissing { object: String, id: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")] FileValidationFailed, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")] MissingFile, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")] MissingFilePurpose, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")] MissingFileContentType, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")] FileNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")] FileNotAvailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")] FileProviderNotSupported, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")] WebhookProcessingError, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")] PaymentMethodUnactivated, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")] HyperswitchUnprocessableEntity { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")] LockTimeout, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")] InvalidTenant, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")] PlatformBadRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")] PlatformUnauthorizedRequest, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes /* AccountCountryInvalidAddress, AccountErrorCountryChangeRequiresAdditionalSteps, AccountInformationMismatch, AccountInvalid, AccountNumberInvalid, AcssDebitSessionIncomplete, AlipayUpgradeRequired, AmountTooLarge, AmountTooSmall, ApiKeyExpired, AuthenticationRequired, BalanceInsufficient, BankAccountBadRoutingNumbers, BankAccountDeclined, BankAccountExists, BankAccountUnusable, BankAccountUnverified, BankAccountVerificationFailed, BillingInvalidMandate, BitcoinUpgradeRequired, CardDeclineRateLimitExceeded, CardDeclined, CardholderPhoneNumberRequired, ChargeAlreadyCaptured, ChargeAlreadyRefunded, ChargeDisputed, ChargeExceedsSourceLimit, ChargeExpiredForCapture, ChargeInvalidParameter, ClearingCodeUnsupported, CountryCodeInvalid, CountryUnsupported, CouponExpired, CustomerMaxPaymentMethods, CustomerMaxSubscriptions, DebitNotAuthorized, EmailInvalid, ExpiredCard, IdempotencyKeyInUse, IncorrectAddress, IncorrectCvc, IncorrectNumber, IncorrectZip, InstantPayoutsConfigDisabled, InstantPayoutsCurrencyDisabled, InstantPayoutsLimitExceeded, InstantPayoutsUnsupported, InsufficientFunds, IntentInvalidState, IntentVerificationMethodMissing, InvalidCardType, InvalidCharacters, InvalidChargeAmount, InvalidCvc, InvalidExpiryMonth, InvalidExpiryYear, InvalidNumber, InvalidSourceUsage, InvoiceNoCustomerLineItems, InvoiceNoPaymentMethodTypes, InvoiceNoSubscriptionLineItems, InvoiceNotEditable, InvoiceOnBehalfOfNotEditable, InvoicePaymentIntentRequiresAction, InvoiceUpcomingNone, LivemodeMismatch, LockTimeout, Missing, NoAccount, NotAllowedOnStandardAccount, OutOfInventory, ParameterInvalidEmpty, ParameterInvalidInteger, ParameterInvalidStringBlank, ParameterInvalidStringEmpty, ParametersExclusive, PaymentIntentActionRequired, PaymentIntentIncompatiblePaymentMethod, PaymentIntentInvalidParameter, PaymentIntentKonbiniRejectedConfirmationNumber, PaymentIntentPaymentAttemptExpired, PaymentIntentUnexpectedState, PaymentMethodBankAccountAlreadyVerified, PaymentMethodBankAccountBlocked, PaymentMethodBillingDetailsAddressMissing, PaymentMethodCurrencyMismatch, PaymentMethodInvalidParameter, PaymentMethodInvalidParameterTestmode, PaymentMethodMicrodepositFailed, PaymentMethodMicrodepositVerificationAmountsInvalid, PaymentMethodMicrodepositVerificationAmountsMismatch, PaymentMethodMicrodepositVerificationAttemptsExceeded, PaymentMethodMicrodepositVerificationDescriptorCodeMismatch, PaymentMethodMicrodepositVerificationTimeout, PaymentMethodProviderDecline, PaymentMethodProviderTimeout, PaymentMethodUnexpectedState, PaymentMethodUnsupportedType, PayoutsNotAllowed, PlatformAccountRequired, PlatformApiKeyExpired, PostalCodeInvalid, ProcessingError, ProductInactive, RateLimit, ReferToCustomer, RefundDisputedPayment, ResourceAlreadyExists, ResourceMissing, ReturnIntentAlreadyProcessed, RoutingNumberInvalid, SecretKeyRequired, SepaUnsupportedAccount, SetupAttemptFailed, SetupIntentAuthenticationFailure, SetupIntentInvalidParameter, SetupIntentSetupAttemptExpired, SetupIntentUnexpectedState, ShippingCalculationFailed, SkuInactive, StateUnsupported, StatusTransitionInvalid, TaxIdInvalid, TaxesCalculationFailed, TerminalLocationCountryUnsupported, TestmodeChargesOnly, TlsVersionUnsupported, TokenInUse, TransferSourceBalanceParametersMismatch, TransfersNotAllowed, */ } impl ::core::fmt::Display for StripeErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{{\"error\": {}}}", serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string()) ) } } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] #[allow(clippy::enum_variant_names)] pub enum StripeErrorType { ApiError, CardError, InvalidRequestError, ConnectorError, HyperswitchError, } impl From<errors::ApiErrorResponse> for StripeErrorCode { fn from(value: errors::ApiErrorResponse) -> Self { match value { errors::ApiErrorResponse::Unauthorized | errors::ApiErrorResponse::InvalidJwtToken | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie | errors::ApiErrorResponse::InvalidEphemeralKey | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin | errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl, errors::ApiErrorResponse::MissingRequiredField { field_name } => { Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), } } errors::ApiErrorResponse::UnprocessableEntity { message } => { Self::HyperswitchUnprocessableEntity { message } } errors::ApiErrorResponse::MissingRequiredFields { field_names } => { // Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String Self::ParameterMissing { field_name: field_names.clone().join(", "), param: field_names.clone().join(", "), } } errors::ApiErrorResponse::GenericNotFoundError { message } => { Self::GenericNotFoundError { message } } errors::ApiErrorResponse::GenericDuplicateError { message } => { Self::GenericDuplicateError { message } } // parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff errors::ApiErrorResponse::InvalidDataFormat { field_name, expected_format, } => Self::ParameterUnknown { field_name, expected_format, }, errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => { Self::RefundAmountExceedsPaymentAmount { param: "amount".to_owned(), } } errors::ApiErrorResponse::PaymentAuthorizationFailed { data } | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => { Self::PaymentIntentAuthenticationFailure { data } } errors::ApiErrorResponse::VerificationFailed { data } => { Self::VerificationFailed { data } } errors::ApiErrorResponse::PaymentCaptureFailed { data } => { Self::PaymentIntentPaymentAttemptFailed { data } } errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data }, errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard, errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed, errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed, errors::ApiErrorResponse::MandateUpdateFailed | errors::ApiErrorResponse::MandateSerializationFailed | errors::ApiErrorResponse::MandateDeserializationFailed | errors::ApiErrorResponse::InternalServerError | errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code errors::ApiErrorResponse::ExternalConnectorError { code, message, connector, status_code, .. } => Self::ExternalConnectorError { code, message, connector, status_code, }, errors::ApiErrorResponse::IncorrectConnectorNameGiven => { Self::IncorrectConnectorNameGiven } errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest, errors::ApiErrorResponse::DuplicatePayout { payout_id } => { Self::DuplicatePayout { payout_id } } errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound, errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound, errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound, errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound, errors::ApiErrorResponse::ClientSecretNotGiven | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => { Self::MerchantConnectorAccountNotFound { id } } errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound, errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound, errors::ApiErrorResponse::EventNotFound => Self::EventNotFound, errors::ApiErrorResponse::MandateValidationFailed { reason } => { Self::PaymentIntentMandateInvalid { message: reason } } errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable, errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount, errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id, connector_label, } => Self::DuplicateMerchantConnectorAccount { profile_id, connector_label, }, errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, errors::ApiErrorResponse::PaymentBlockedError { code, message, status, reason, } => Self::PaymentBlockedError { code, message, status, reason, }, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { param: "client_secret".to_owned(), }, errors::ApiErrorResponse::InvalidRequestData { message } => { Self::InvalidRequestData { message } } errors::ApiErrorResponse::PreconditionFailed { message } => { Self::PreconditionFailed { message } } errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), }, errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount, errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed, errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate, errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound, errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound, errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized, errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::PaymentUnexpectedState { current_flow, field_name, current_value, states, } => Self::PaymentIntentUnexpectedState { current_flow, field_name, current_value, states, }, errors::ApiErrorResponse::DuplicatePayment { payment_id } => { Self::DuplicatePayment { payment_id } } errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing { object: "dispute".to_owned(), id: dispute_id, }, errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing { object: "authentication".to_owned(), id, }, errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing { object: "business_profile".to_owned(), id, }, errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing { object: "poll".to_owned(), id, }, errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => { Self::InternalServerError } errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed, errors::ApiErrorResponse::MissingFile => Self::MissingFile, errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose, errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType, errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId, errors::ApiErrorResponse::FileNotFound => Self::FileNotFound, errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable, errors::ApiErrorResponse::MerchantConnectorAccountDisabled => { Self::MerchantConnectorAccountDisabled } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::CurrencyNotSupported { message } => { Self::CurrencyNotSupported { message } } errors::ApiErrorResponse::FileProviderNotSupported { .. } => { Self::FileProviderNotSupported } errors::ApiErrorResponse::WebhookBadRequest | errors::ApiErrorResponse::WebhookResourceNotFound | errors::ApiErrorResponse::WebhookProcessingFailure | errors::ApiErrorResponse::WebhookAuthenticationFailed | errors::ApiErrorResponse::WebhookUnprocessableEntity | errors::ApiErrorResponse::WebhookInvalidMerchantSecret => { Self::WebhookProcessingError } errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => { Self::PaymentMethodUnactivated } errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated, errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => { Self::InvalidConnectorConfiguration { config } } errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed, errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed, errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => { Self::InvalidWalletToken { wallet_name } } errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound, errors::ApiErrorResponse::LinkConfigurationError { message } => { Self::LinkConfigurationError { message } } errors::ApiErrorResponse::IntegrityCheckFailed { reason, field_names, connector_transaction_id, } => Self::IntegrityCheckFailed { reason, field_names, connector_transaction_id, }, errors::ApiErrorResponse::InvalidTenant { tenant_id: _ } | errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant, errors::ApiErrorResponse::AmountConversionFailed { amount_type } => { Self::AmountConversionFailed { amount_type } } errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest, errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest, } } } impl actix_web::ResponseError for StripeErrorCode { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; match self { Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED, Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND, Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => { StatusCode::UNPROCESSABLE_ENTITY } Self::ParameterMissing { .. } | Self::RefundAmountExceedsPaymentAmount { .. } | Self::PaymentIntentAuthenticationFailure { .. } | Self::PaymentIntentPaymentAttemptFailed { .. } | Self::ExpiredCard | Self::InvalidCardType | Self::DuplicateRefundRequest | Self::DuplicatePayout { .. } | Self::RefundNotFound | Self::CustomerNotFound | Self::ConfigNotFound | Self::DuplicateConfig | Self::ClientSecretNotFound | Self::PaymentNotFound | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound { .. } | Self::MerchantConnectorAccountDisabled | Self::MandateNotFound | Self::ApiKeyNotFound | Self::PayoutNotFound | Self::EventNotFound | Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod | Self::PaymentFailed | Self::VerificationFailed { .. } | Self::DisputeFailed { .. } | Self::MaximumRefundCount | Self::PaymentIntentInvalidParameter { .. } | Self::SerdeQsError { .. } | Self::InvalidRequestData { .. } | Self::InvalidWalletToken { .. } | Self::PreconditionFailed { .. } | Self::DuplicateMandate | Self::SuccessfulPaymentNotFound | Self::AddressNotFound | Self::ResourceIdNotFound | Self::PaymentIntentMandateInvalid { .. } | Self::PaymentIntentUnexpectedState { .. } | Self::DuplicatePayment { .. } | Self::GenericDuplicateError { .. } | Self::IncorrectConnectorNameGiven | Self::ResourceMissing { .. } | Self::FileValidationFailed | Self::MissingFile | Self::MissingFileContentType | Self::MissingFilePurpose | Self::MissingDisputeId | Self::FileNotFound | Self::FileNotAvailable | Self::FileProviderNotSupported | Self::CurrencyNotSupported { .. } | Self::DuplicateCustomer | Self::PaymentMethodUnactivated | Self::InvalidConnectorConfiguration { .. } | Self::CurrencyConversionFailed | Self::PaymentMethodDeleteFailed | Self::ExtendedCardInfoNotFound | Self::PlatformBadRequest | Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound | Self::InternalServerError | Self::MandateActive | Self::CustomerRedacted | Self::WebhookProcessingError | Self::InvalidTenant | Self::AmountConversionFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) } Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::PaymentBlockedError { code, .. } => { StatusCode::from_u16(*code).unwrap_or(StatusCode::OK) } Self::LockTimeout => StatusCode::LOCKED, } } fn error_response(&self) -> actix_web::HttpResponse { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } impl From<serde_qs::Error> for StripeErrorCode { fn from(item: serde_qs::Error) -> Self { match item { serde_qs::Error::Custom(s) => Self::SerdeQsError { error_message: s, param: None, }, serde_qs::Error::Parse(param, position) => Self::SerdeQsError { error_message: format!( "parsing failed with error: '{param}' at position: {position}" ), param: Some(param), }, serde_qs::Error::Unsupported => Self::SerdeQsError { error_message: "Given request format is not supported".to_owned(), param: None, }, serde_qs::Error::FromUtf8(_) => Self::SerdeQsError { error_message: "Failed to parse request to from utf-8".to_owned(), param: None, }, serde_qs::Error::Io(_) => Self::SerdeQsError { error_message: "Failed to parse request".to_owned(), param: None, }, serde_qs::Error::ParseInt(_) => Self::SerdeQsError { error_message: "Failed to parse integer in request".to_owned(), param: None, }, serde_qs::Error::Utf8(_) => Self::SerdeQsError { error_message: "Failed to convert utf8 to string".to_owned(), param: None, }, } } } impl ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse { fn switch(&self) -> StripeErrorCode { self.clone().into() } } impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {} impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse { fn switch(&self) -> StripeErrorCode { use StripeErrorCode as SC; match self { Self::CustomerRedacted => SC::CustomerRedacted, Self::InternalServerError => SC::InternalServerError, Self::MandateActive => SC::MandateActive, Self::CustomerNotFound => SC::CustomerNotFound, Self::CustomerAlreadyExists => SC::DuplicateCustomer, } } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=ApiError roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/errors.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=ApiError roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum StripeErrorCode { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/errors.rs" crate="router" role="use_site"> <|fim_prefix|> pub enum StripeErrorCode { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=ApiError roles=macro_def,use_site use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> impl From<ring::error::Unspecified> for EncryptionError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" crate="router" role="use_site"> <|fim_prefix|> impl From<ring::error::Unspecified> for EncryptionError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" crate="router" role="use_site"> impl_error_type!(EncryptionError, "Encryption error"); <file_sep path="hyperswitch/crates/router/src/core/errors.rs" crate="router" role="use_site"> impl_error_type!(EncryptionError, "Encryption error"); <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=ApiError roles=use_site,macro_def use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::ApiClientError => super::DataEncryptionError); <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::ApiClientError => super::DataEncryptionError); <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> src macro=ApiError roles=use_site,macro_def use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::ApiClientError => super::KeyManagerHealthCheckError); <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::ApiClientError => super::KeyManagerHealthCheckError); <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> src macro=ApiError roles=use_site,macro_def use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::DataDecryptionError => super::KeyManagerError); <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::DataDecryptionError => super::KeyManagerError); <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> src macro=ApiError roles=use_site,macro_def use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> src macro=ApiError roles=macro_def,use_site use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> impl<'a> From<&'a super::CryptoError> for super::MerchantDBError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> <|fim_prefix|> impl<'a> From<&'a super::CryptoError> for super::MerchantDBError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> src macro=ApiError roles=macro_def,use_site use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> impl<'a> From<&'a super::CryptoError> for super::MerchantDBError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> <|fim_prefix|> impl<'a> From<&'a super::CryptoError> for super::MerchantDBError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> src macro=ApiError roles=macro_def,use_site use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> impl<'a> From<&'a super::CryptoError> for super::MerchantDBError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> <|fim_prefix|> impl<'a> From<&'a super::CryptoError> for super::MerchantDBError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/errors/api_error_response.rs" crate="hyperswitch_domain_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> hyperswitch_domain_models macro=ApiError roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ErrorType { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/hyperswitch_domain_models/src/errors/api_error_response.rs" crate="hyperswitch_domain_models" role="use_site"> <|fim_prefix|> pub enum ErrorType { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router/src/routes/dummy_connector/errors.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> router macro=ApiError roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ErrorType { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/routes/dummy_connector/errors.rs" crate="router" role="use_site"> <|fim_prefix|> pub enum ErrorType { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::ApiClientError => super::DataDecryptionError); <file_sep path="hyperswitch-card-vault/src/error/transforms.rs" crate="src" role="use_site"> error_transform!(super::ApiClientError => super::DataDecryptionError); <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> src macro=ApiError roles=use_site,macro_def use=invoke item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/diesel_models/src/user_authentication_method.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=Setter roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct UserAuthenticationMethod { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/user_authentication_method.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub struct UserAuthenticationMethod { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/diesel_models/src/user_authentication_method.rs" crate="diesel_models" role="use_site"> use common_utils::encryption::Encryption; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::user_authentication_methods}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))] pub struct UserAuthenticationMethod { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct UserAuthenticationMethodNew { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct OrgAuthenticationMethodUpdateInternal { pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub last_modified_at: PrimitiveDateTime, pub email_domain: Option<String>, } pub enum UserAuthenticationMethodUpdate { UpdateConfig { private_config: Option<Encryption>, public_config: Option<serde_json::Value>, }, EmailDomain { email_domain: String, }, } impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal { fn from(value: UserAuthenticationMethodUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match value { UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, } => Self { private_config, public_config, last_modified_at, email_domain: None, }, UserAuthenticationMethodUpdate::EmailDomain { email_domain } => Self { private_config: None, public_config: None, last_modified_at, email_domain: Some(email_domain), }, } } } <file_sep path="hyperswitch/crates/diesel_models/src/user_authentication_method.rs" crate="diesel_models" role="use_site"> use common_utils::encryption::Encryption; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::user_authentication_methods}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))] pub struct UserAuthenticationMethod { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct UserAuthenticationMethodNew { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct OrgAuthenticationMethodUpdateInternal { pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub last_modified_at: PrimitiveDateTime, pub email_domain: Option<String>, } pub enum UserAuthenticationMethodUpdate { UpdateConfig { private_config: Option<Encryption>, public_config: Option<serde_json::Value>, }, EmailDomain { email_domain: String, }, } impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal { fn from(value: UserAuthenticationMethodUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match value { UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, } => Self { private_config, public_config, last_modified_at, email_domain: None, }, UserAuthenticationMethodUpdate::EmailDomain { email_domain } => Self { private_config: None, public_config: None, last_modified_at, email_domain: Some(email_domain), }, } } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> <|fim_prefix|> pub enum PaymentOp { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/diesel_models/src/fraud_check.rs" crate="diesel_models" role="use_site"> use common_enums as storage_enums; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, schema::fraud_check, }; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FraudCheck { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckNew { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum FraudCheckUpdate { //Refer PaymentAttemptUpdate for other variants implementations ResponseUpdate { frm_status: FraudCheckStatus, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, metadata: Option<serde_json::Value>, modified_at: PrimitiveDateTime, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, }, ErrorUpdate { status: FraudCheckStatus, error_message: Option<Option<String>>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckUpdateInternal { frm_status: Option<FraudCheckStatus>, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, frm_error: Option<Option<String>>, metadata: Option<serde_json::Value>, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, } impl From<FraudCheckUpdate> for FraudCheckUpdateInternal { fn from(fraud_check_update: FraudCheckUpdate) -> Self { match fraud_check_update { FraudCheckUpdate::ResponseUpdate { frm_status, frm_transaction_id, frm_reason, frm_score, metadata, modified_at: _, last_step, payment_capture_method, } => Self { frm_status: Some(frm_status), frm_transaction_id, frm_reason, frm_score, metadata, last_step, payment_capture_method, ..Default::default() }, FraudCheckUpdate::ErrorUpdate { status, error_message, } => Self { frm_status: Some(status), frm_error: error_message, ..Default::default() }, } } } <file_sep path="hyperswitch/crates/diesel_models/src/fraud_check.rs" crate="diesel_models" role="use_site"> use common_enums as storage_enums; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, schema::fraud_check, }; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FraudCheck { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckNew { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum FraudCheckUpdate { //Refer PaymentAttemptUpdate for other variants implementations ResponseUpdate { frm_status: FraudCheckStatus, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, metadata: Option<serde_json::Value>, modified_at: PrimitiveDateTime, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, }, ErrorUpdate { status: FraudCheckStatus, error_message: Option<Option<String>>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckUpdateInternal { frm_status: Option<FraudCheckStatus>, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, frm_error: Option<Option<String>>, metadata: Option<serde_json::Value>, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, } impl From<FraudCheckUpdate> for FraudCheckUpdateInternal { fn from(fraud_check_update: FraudCheckUpdate) -> Self { match fraud_check_update { FraudCheckUpdate::ResponseUpdate { frm_status, frm_transaction_id, frm_reason, frm_score, metadata, modified_at: _, last_step, payment_capture_method, } => Self { frm_status: Some(frm_status), frm_transaction_id, frm_reason, frm_score, metadata, last_step, payment_capture_method, ..Default::default() }, FraudCheckUpdate::ErrorUpdate { status, error_message, } => Self { frm_status: Some(status), frm_error: error_message, ..Default::default() }, } } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" crate="api_models" role="use_site"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment 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 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> api_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/diesel_models/src/role.rs" crate="diesel_models" role="use_site"> use common_utils::id_type; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::roles}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))] pub struct Role { pub role_name: String, pub role_id: String, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleNew { pub role_name: String, pub role_id: String, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleUpdateInternal { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_by: String, last_modified_at: PrimitiveDateTime, } pub enum RoleUpdate { UpdateDetails { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_at: PrimitiveDateTime, last_modified_by: String, }, } impl From<RoleUpdate> for RoleUpdateInternal { fn from(value: RoleUpdate) -> Self { match value { RoleUpdate::UpdateDetails { groups, role_name, last_modified_by, last_modified_at, } => Self { groups, role_name, last_modified_at, last_modified_by, }, } } } #[derive(Clone, Debug)] pub enum ListRolesByEntityPayload { Profile(id_type::MerchantId, id_type::ProfileId), Merchant(id_type::MerchantId), Organization, } <file_sep path="hyperswitch/crates/diesel_models/src/role.rs" crate="diesel_models" role="use_site"> use common_utils::id_type; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::roles}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))] pub struct Role { pub role_name: String, pub role_id: String, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleNew { pub role_name: String, pub role_id: String, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleUpdateInternal { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_by: String, last_modified_at: PrimitiveDateTime, } pub enum RoleUpdate { UpdateDetails { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_at: PrimitiveDateTime, last_modified_by: String, }, } impl From<RoleUpdate> for RoleUpdateInternal { fn from(value: RoleUpdate) -> Self { match value { RoleUpdate::UpdateDetails { groups, role_name, last_modified_by, last_modified_at, } => Self { groups, role_name, last_modified_at, last_modified_by, }, } } } #[derive(Clone, Debug)] pub enum ListRolesByEntityPayload { Profile(id_type::MerchantId, id_type::ProfileId), Merchant(id_type::MerchantId), Organization, } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=Setter roles=use_site,macro_def use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/diesel_models/src/user_role.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=Setter roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct UserRole { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/user_role.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub struct UserRole { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/diesel_models/src/role.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=Setter roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct Role { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/role.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub struct Role { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } <file_sep path="hyperswitch/crates/diesel_models/src/fraud_check.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=Setter roles=macro_def,use_site use=derive item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub struct FraudCheck { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/fraud_check.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub struct FraudCheck { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> mod accounts; mod payments; mod ui; use std::num::{ParseFloatError, TryFromIntError}; pub use accounts::MerchantProductType; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::RoutableConnectors; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending => false, } } } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SessionUpdateStatus { Success, Failure, } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request Manual, /// The capture will happen only if the merchant triggers a Capture API request ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time Scheduled, /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), } /// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentAuthorized, PaymentCaptured, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, PayoutSuccess, PayoutFailed, PayoutInitiated, PayoutProcessing, PayoutCancelled, PayoutExpired, PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// The status of the current payment that was made #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured | Self::RequiresCapture => false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable => true, } } } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. /// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment /// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Boleto, BcaBankTransfer, BniVa, BriVa, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::BriVa => "BRI Virtual Account", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, False, #[default] Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa => false, Self::Gpayments => true, } } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/common_enums/src/enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> pub enum ApplicationError { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbCardDiscovery as CardDiscovery, DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDashboardMetadata as DashboardMetadata, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType, DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme, DbOrderFulfillmentTimeOrigin as OrderFulfillmentTimeOrigin, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentSource as PaymentSource, DbPaymentType as PaymentType, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType, DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus, DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRelayStatus as RelayStatus, DbRelayType as RelayType, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub use common_enums::*; use common_utils::pii; use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb}; use router_derive::diesel_enum; use time::PrimitiveDateTime; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventObjectType { PaymentDetails, RefundDetails, DisputeDetails, MandateDetails, PayoutDetails, } // Refund #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundType { InstantRefund, #[default] RegularRefund, RetryRefund, } // Mandate #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateType { SingleUse, #[default] MultiUse, } #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, } common_utils::impl_to_sql_from_sql_json!(MandateDetails); #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { SingleUse(MandateAmountData), MultiUse(Option<MandateAmountData>), } common_utils::impl_to_sql_from_sql_json!(MandateDataType); #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: common_utils::types::MinorUnit, pub currency: Currency, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckType { PreFrm, PostFrm, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckLastStep { #[default] Processing, CheckoutOrSale, TransactionOrRecordRefund, Fulfillment, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserStatus { Active, #[default] InvitationSent, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DashboardMetadata { ProductionAgreement, SetupProcessor, ConfigureEndpoint, SetupComplete, FirstProcessorConnected, SecondProcessorConnected, ConfiguredRouting, TestPayment, IntegrationMethod, ConfigurationType, IntegrationCompleted, StripeConnected, PaypalConnected, SpRoutingConfigured, Feedback, ProdIntent, SpTestPayment, DownloadWoocom, ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, IsChangePasswordRequired, OnboardingSurvey, ReconStatus, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TotpStatus { Set, InProgress, #[default] NotSet, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::EnumString, strum::Display, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserRoleVersion { #[default] V1, V2, } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbCardDiscovery as CardDiscovery, DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDashboardMetadata as DashboardMetadata, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType, DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme, DbOrderFulfillmentTimeOrigin as OrderFulfillmentTimeOrigin, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentSource as PaymentSource, DbPaymentType as PaymentType, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType, DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus, DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRelayStatus as RelayStatus, DbRelayType as RelayType, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub use common_enums::*; use common_utils::pii; use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb}; use router_derive::diesel_enum; use time::PrimitiveDateTime; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventObjectType { PaymentDetails, RefundDetails, DisputeDetails, MandateDetails, PayoutDetails, } // Refund #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundType { InstantRefund, #[default] RegularRefund, RetryRefund, } // Mandate #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateType { SingleUse, #[default] MultiUse, } #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, } common_utils::impl_to_sql_from_sql_json!(MandateDetails); #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { SingleUse(MandateAmountData), MultiUse(Option<MandateAmountData>), } common_utils::impl_to_sql_from_sql_json!(MandateDataType); #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: common_utils::types::MinorUnit, pub currency: Currency, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckType { PreFrm, PostFrm, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckLastStep { #[default] Processing, CheckoutOrSale, TransactionOrRecordRefund, Fulfillment, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserStatus { Active, #[default] InvitationSent, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DashboardMetadata { ProductionAgreement, SetupProcessor, ConfigureEndpoint, SetupComplete, FirstProcessorConnected, SecondProcessorConnected, ConfiguredRouting, TestPayment, IntegrationMethod, ConfigurationType, IntegrationCompleted, StripeConnected, PaypalConnected, SpRoutingConfigured, Feedback, ProdIntent, SpTestPayment, DownloadWoocom, ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, IsChangePasswordRequired, OnboardingSurvey, ReconStatus, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TotpStatus { Set, InProgress, #[default] NotSet, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::EnumString, strum::Display, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserRoleVersion { #[default] V1, V2, } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/common_enums/src/connector_enums.rs" crate="common_enums" role="use_site"> use std::collections::HashSet; use utoipa::ToSchema; pub use super::enums::{PaymentMethod, PayoutType}; pub use crate::PaymentMethodType; #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] /// RoutableConnectors are the subset of Connectors that are eligible for payments routing pub enum RoutableConnectors { Adyenplatform, #[cfg(feature = "dummy_connector")] #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] DummyConnector1, #[cfg(feature = "dummy_connector")] #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] DummyConnector2, #[cfg(feature = "dummy_connector")] #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] DummyConnector3, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_test")] #[strum(serialize = "stripe_test")] DummyConnector4, #[cfg(feature = "dummy_connector")] #[serde(rename = "adyen_test")] #[strum(serialize = "adyen_test")] DummyConnector5, #[cfg(feature = "dummy_connector")] #[serde(rename = "checkout_test")] #[strum(serialize = "checkout_test")] DummyConnector6, #[cfg(feature = "dummy_connector")] #[serde(rename = "paypal_test")] #[strum(serialize = "paypal_test")] DummyConnector7, Aci, Adyen, Airwallex, // Amazonpay, Authorizedotnet, Bankofamerica, Billwerk, Bitpay, Bambora, Bamboraapac, Bluesnap, Boku, Braintree, Cashtocode, Chargebee, Checkout, Coinbase, Coingate, Cryptopay, Cybersource, Datatrans, Deutschebank, Digitalvirgo, Dlocal, Ebanx, Elavon, // Facilitapay, Fiserv, Fiservemea, Fiuu, Forte, Getnet, Globalpay, Globepay, Gocardless, Hipay, Helcim, Iatapay, Inespay, Itaubank, Jpmorgan, Klarna, Mifinity, Mollie, Moneris, Multisafepay, Nexinets, Nexixpay, Nmi, Nomupay, Noon, Novalnet, Nuvei, // Opayo, added as template code for future usage Opennode, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Paybox, Payme, Payone, Paypal, Paystack, Payu, Placetopay, Powertranz, Prophetpay, Rapyd, Razorpay, Recurly, Redsys, Riskified, Shift4, Signifyd, Square, Stax, Stripe, Stripebilling, // Taxjar, Trustpay, // Thunes // Tsys, Tsys, // UnifiedAuthenticationService, Volt, Wellsfargo, // Wellsfargopayout, Wise, Worldline, Worldpay, Xendit, Zen, Plaid, Zsl, } // A connector is an integration to fulfill payments #[derive( Clone, Copy, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::VariantNames, strum::EnumIter, strum::Display, strum::EnumString, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum Connector { Adyenplatform, #[cfg(feature = "dummy_connector")] #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] DummyConnector1, #[cfg(feature = "dummy_connector")] #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] DummyConnector2, #[cfg(feature = "dummy_connector")] #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] DummyConnector3, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_test")] #[strum(serialize = "stripe_test")] DummyConnector4, #[cfg(feature = "dummy_connector")] #[serde(rename = "adyen_test")] #[strum(serialize = "adyen_test")] DummyConnector5, #[cfg(feature = "dummy_connector")] #[serde(rename = "checkout_test")] #[strum(serialize = "checkout_test")] DummyConnector6, #[cfg(feature = "dummy_connector")] #[serde(rename = "paypal_test")] #[strum(serialize = "paypal_test")] DummyConnector7, Aci, Adyen, Airwallex, // Amazonpay, Authorizedotnet, Bambora, Bamboraapac, Bankofamerica, Billwerk, Bitpay, Bluesnap, Boku, Braintree, Cashtocode, Chargebee, Checkout, Coinbase, Coingate, Cryptopay, CtpMastercard, CtpVisa, Cybersource, Datatrans, Deutschebank, Digitalvirgo, Dlocal, Ebanx, Elavon, // Facilitapay, Fiserv, Fiservemea, Fiuu, Forte, Getnet, Globalpay, Globepay, Gocardless, Gpayments, Hipay, Helcim, Inespay, Iatapay, Itaubank, Jpmorgan, Juspaythreedsserver, Klarna, Mifinity, Mollie, Moneris, Multisafepay, Netcetera, Nexinets, Nexixpay, Nmi, Nomupay, Noon, Novalnet, Nuvei, // Opayo, added as template code for future usage Opennode, Paybox, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Payme, Payone, Paypal, Paystack, Payu, Placetopay, Powertranz, Prophetpay, Rapyd, Razorpay, Recurly, Redsys, Shift4, Square, Stax, Stripe, Stripebilling, Taxjar, Threedsecureio, //Thunes, Trustpay, Tsys, // UnifiedAuthenticationService, Volt, Wellsfargo, // Wellsfargopayout, Wise, Worldline, Worldpay, Signifyd, Plaid, Riskified, Xendit, Zen, Zsl, } impl Connector { #[cfg(feature = "payouts")] pub fn supports_instant_payout(self, payout_method: Option<PayoutType>) -> bool { matches!( (self, payout_method), (Self::Paypal, Some(PayoutType::Wallet)) | (_, Some(PayoutType::Card)) | (Self::Adyenplatform, _) | (Self::Nomupay, _) ) } #[cfg(feature = "payouts")] pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Bank))) } #[cfg(feature = "payouts")] pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Card))) } #[cfg(feature = "payouts")] pub fn is_payout_quote_call_required(self) -> bool { matches!(self, Self::Wise) } #[cfg(feature = "payouts")] pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (Self::Paypal, _)) } #[cfg(feature = "payouts")] pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool { matches!(self, Self::Stripe | Self::Nomupay) } pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool { matches!( (self, payment_method), (Self::Airwallex, _) | (Self::Deutschebank, _) | (Self::Globalpay, _) | (Self::Jpmorgan, _) | (Self::Moneris, _) | (Self::Paypal, _) | (Self::Payu, _) | ( Self::Trustpay, PaymentMethod::BankRedirect | PaymentMethod::BankTransfer ) | (Self::Iatapay, _) | (Self::Volt, _) | (Self::Itaubank, _) ) } pub fn supports_file_storage_module(self) -> bool { matches!(self, Self::Stripe | Self::Checkout) } pub fn requires_defend_dispute(self) -> bool { matches!(self, Self::Checkout) } pub fn is_separate_authentication_supported(self) -> bool { match self { #[cfg(feature = "dummy_connector")] Self::DummyConnector1 | Self::DummyConnector2 | Self::DummyConnector3 | Self::DummyConnector4 | Self::DummyConnector5 | Self::DummyConnector6 | Self::DummyConnector7 => false, Self::Aci // Add Separate authentication support for connectors | Self::Adyen | Self::Adyenplatform | Self::Airwallex // | Self::Amazonpay | Self::Authorizedotnet | Self::Bambora | Self::Bamboraapac | Self::Bankofamerica | Self::Billwerk | Self::Bitpay | Self::Bluesnap | Self::Boku | Self::Braintree | Self::Cashtocode | Self::Chargebee | Self::Coinbase | Self::Coingate | Self::Cryptopay | Self::Deutschebank | Self::Digitalvirgo | Self::Dlocal | Self::Ebanx | Self::Elavon // | Self::Facilitapay | Self::Fiserv | Self::Fiservemea | Self::Fiuu | Self::Forte | Self::Getnet | Self::Globalpay | Self::Globepay | Self::Gocardless | Self::Gpayments | Self::Hipay | Self::Helcim | Self::Iatapay | Self::Inespay | Self::Itaubank | Self::Jpmorgan | Self::Juspaythreedsserver | Self::Klarna | Self::Mifinity | Self::Mollie | Self::Moneris | Self::Multisafepay | Self::Nexinets | Self::Nexixpay | Self::Nomupay | Self::Novalnet | Self::Nuvei | Self::Opennode | Self::Paybox | Self::Payme | Self::Payone | Self::Paypal | Self::Paystack | Self::Payu | Self::Placetopay | Self::Powertranz | Self::Prophetpay | Self::Rapyd | Self::Recurly | Self::Redsys | Self::Shift4 | Self::Square | Self::Stax | Self::Stripebilling | Self::Taxjar // | Self::Thunes | Self::Trustpay | Self::Tsys // | Self::UnifiedAuthenticationService | Self::Volt | Self::Wellsfargo // | Self::Wellsfargopayout | Self::Wise | Self::Worldline | Self::Worldpay | Self::Xendit | Self::Zen | Self::Zsl | Self::Signifyd | Self::Plaid | Self::Razorpay | Self::Riskified | Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::CtpVisa | Self::Noon | Self::Stripe | Self::Datatrans => false, Self::Checkout | Self::Nmi |Self::Cybersource => true, } } pub fn is_pre_processing_required_before_authorize(self) -> bool { matches!(self, Self::Airwallex) } pub fn get_payment_methods_supporting_extended_authorization(self) -> HashSet<PaymentMethod> { HashSet::new() } pub fn get_payment_method_types_supporting_extended_authorization( self, ) -> HashSet<PaymentMethodType> { HashSet::new() } pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool { matches!(self, Self::Adyenplatform) } /// Validates if dummy connector can be created /// Dummy connectors can be created only if dummy_connector feature is enabled in the configs #[cfg(feature = "dummy_connector")] pub fn validate_dummy_connector_create(self, is_dummy_connector_enabled: bool) -> bool { matches!( self, Self::DummyConnector1 | Self::DummyConnector2 | Self::DummyConnector3 | Self::DummyConnector4 | Self::DummyConnector5 | Self::DummyConnector6 | Self::DummyConnector7 ) && !is_dummy_connector_enabled } } /// Convert the RoutableConnectors to Connector impl From<RoutableConnectors> for Connector { fn from(routable_connector: RoutableConnectors) -> Self { match routable_connector { RoutableConnectors::Adyenplatform => Self::Adyenplatform, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector1 => Self::DummyConnector1, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector2 => Self::DummyConnector2, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector3 => Self::DummyConnector3, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector4 => Self::DummyConnector4, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector5 => Self::DummyConnector5, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector6 => Self::DummyConnector6, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector7 => Self::DummyConnector7, RoutableConnectors::Aci => Self::Aci, RoutableConnectors::Adyen => Self::Adyen, RoutableConnectors::Airwallex => Self::Airwallex, RoutableConnectors::Authorizedotnet => Self::Authorizedotnet, RoutableConnectors::Bankofamerica => Self::Bankofamerica, RoutableConnectors::Billwerk => Self::Billwerk, RoutableConnectors::Bitpay => Self::Bitpay, RoutableConnectors::Bambora => Self::Bambora, RoutableConnectors::Bamboraapac => Self::Bamboraapac, RoutableConnectors::Bluesnap => Self::Bluesnap, RoutableConnectors::Boku => Self::Boku, RoutableConnectors::Braintree => Self::Braintree, RoutableConnectors::Cashtocode => Self::Cashtocode, RoutableConnectors::Chargebee => Self::Chargebee, RoutableConnectors::Checkout => Self::Checkout, RoutableConnectors::Coinbase => Self::Coinbase, RoutableConnectors::Cryptopay => Self::Cryptopay, RoutableConnectors::Cybersource => Self::Cybersource, RoutableConnectors::Datatrans => Self::Datatrans, RoutableConnectors::Deutschebank => Self::Deutschebank, RoutableConnectors::Digitalvirgo => Self::Digitalvirgo, RoutableConnectors::Dlocal => Self::Dlocal, RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, // RoutableConnectors::Facilitapay => Self::Facilitapay, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, RoutableConnectors::Forte => Self::Forte, RoutableConnectors::Getnet => Self::Getnet, RoutableConnectors::Globalpay => Self::Globalpay, RoutableConnectors::Globepay => Self::Globepay, RoutableConnectors::Gocardless => Self::Gocardless, RoutableConnectors::Helcim => Self::Helcim, RoutableConnectors::Iatapay => Self::Iatapay, RoutableConnectors::Itaubank => Self::Itaubank, RoutableConnectors::Jpmorgan => Self::Jpmorgan, RoutableConnectors::Klarna => Self::Klarna, RoutableConnectors::Mifinity => Self::Mifinity, RoutableConnectors::Mollie => Self::Mollie, RoutableConnectors::Moneris => Self::Moneris, RoutableConnectors::Multisafepay => Self::Multisafepay, RoutableConnectors::Nexinets => Self::Nexinets, RoutableConnectors::Nexixpay => Self::Nexixpay, RoutableConnectors::Nmi => Self::Nmi, RoutableConnectors::Nomupay => Self::Nomupay, RoutableConnectors::Noon => Self::Noon, RoutableConnectors::Novalnet => Self::Novalnet, RoutableConnectors::Nuvei => Self::Nuvei, RoutableConnectors::Opennode => Self::Opennode, RoutableConnectors::Paybox => Self::Paybox, RoutableConnectors::Payme => Self::Payme, RoutableConnectors::Payone => Self::Payone, RoutableConnectors::Paypal => Self::Paypal, RoutableConnectors::Paystack => Self::Paystack, RoutableConnectors::Payu => Self::Payu, RoutableConnectors::Placetopay => Self::Placetopay, RoutableConnectors::Powertranz => Self::Powertranz, RoutableConnectors::Prophetpay => Self::Prophetpay, RoutableConnectors::Rapyd => Self::Rapyd, RoutableConnectors::Razorpay => Self::Razorpay, RoutableConnectors::Recurly => Self::Recurly, RoutableConnectors::Redsys => Self::Redsys, RoutableConnectors::Riskified => Self::Riskified, RoutableConnectors::Shift4 => Self::Shift4, RoutableConnectors::Signifyd => Self::Signifyd, RoutableConnectors::Square => Self::Square, RoutableConnectors::Stax => Self::Stax, RoutableConnectors::Stripe => Self::Stripe, RoutableConnectors::Stripebilling => Self::Stripebilling, RoutableConnectors::Trustpay => Self::Trustpay, RoutableConnectors::Tsys => Self::Tsys, RoutableConnectors::Volt => Self::Volt, RoutableConnectors::Wellsfargo => Self::Wellsfargo, RoutableConnectors::Wise => Self::Wise, RoutableConnectors::Worldline => Self::Worldline, RoutableConnectors::Worldpay => Self::Worldpay, RoutableConnectors::Zen => Self::Zen, RoutableConnectors::Plaid => Self::Plaid, RoutableConnectors::Zsl => Self::Zsl, RoutableConnectors::Xendit => Self::Xendit, RoutableConnectors::Inespay => Self::Inespay, RoutableConnectors::Coingate => Self::Coingate, RoutableConnectors::Hipay => Self::Hipay, } } } impl TryFrom<Connector> for RoutableConnectors { type Error = &'static str; fn try_from(connector: Connector) -> Result<Self, Self::Error> { match connector { Connector::Adyenplatform => Ok(Self::Adyenplatform), #[cfg(feature = "dummy_connector")] Connector::DummyConnector1 => Ok(Self::DummyConnector1), #[cfg(feature = "dummy_connector")] Connector::DummyConnector2 => Ok(Self::DummyConnector2), #[cfg(feature = "dummy_connector")] Connector::DummyConnector3 => Ok(Self::DummyConnector3), #[cfg(feature = "dummy_connector")] Connector::DummyConnector4 => Ok(Self::DummyConnector4), #[cfg(feature = "dummy_connector")] Connector::DummyConnector5 => Ok(Self::DummyConnector5), #[cfg(feature = "dummy_connector")] Connector::DummyConnector6 => Ok(Self::DummyConnector6), #[cfg(feature = "dummy_connector")] Connector::DummyConnector7 => Ok(Self::DummyConnector7), Connector::Aci => Ok(Self::Aci), Connector::Adyen => Ok(Self::Adyen), Connector::Airwallex => Ok(Self::Airwallex), Connector::Authorizedotnet => Ok(Self::Authorizedotnet), Connector::Bankofamerica => Ok(Self::Bankofamerica), Connector::Billwerk => Ok(Self::Billwerk), Connector::Bitpay => Ok(Self::Bitpay), Connector::Bambora => Ok(Self::Bambora), Connector::Bamboraapac => Ok(Self::Bamboraapac), Connector::Bluesnap => Ok(Self::Bluesnap), Connector::Boku => Ok(Self::Boku), Connector::Braintree => Ok(Self::Braintree), Connector::Cashtocode => Ok(Self::Cashtocode), Connector::Chargebee => Ok(Self::Chargebee), Connector::Checkout => Ok(Self::Checkout), Connector::Coinbase => Ok(Self::Coinbase), Connector::Coingate => Ok(Self::Coingate), Connector::Cryptopay => Ok(Self::Cryptopay), Connector::Cybersource => Ok(Self::Cybersource), Connector::Datatrans => Ok(Self::Datatrans), Connector::Deutschebank => Ok(Self::Deutschebank), Connector::Digitalvirgo => Ok(Self::Digitalvirgo), Connector::Dlocal => Ok(Self::Dlocal), Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), // Connector::Facilitapay => Ok(Self::Facilitapay), Connector::Fiserv => Ok(Self::Fiserv), Connector::Fiservemea => Ok(Self::Fiservemea), Connector::Fiuu => Ok(Self::Fiuu), Connector::Forte => Ok(Self::Forte), Connector::Globalpay => Ok(Self::Globalpay), Connector::Globepay => Ok(Self::Globepay), Connector::Gocardless => Ok(Self::Gocardless), Connector::Helcim => Ok(Self::Helcim), Connector::Iatapay => Ok(Self::Iatapay), Connector::Itaubank => Ok(Self::Itaubank), Connector::Jpmorgan => Ok(Self::Jpmorgan), Connector::Klarna => Ok(Self::Klarna), Connector::Mifinity => Ok(Self::Mifinity), Connector::Mollie => Ok(Self::Mollie), Connector::Moneris => Ok(Self::Moneris), Connector::Multisafepay => Ok(Self::Multisafepay), Connector::Nexinets => Ok(Self::Nexinets), Connector::Nexixpay => Ok(Self::Nexixpay), Connector::Nmi => Ok(Self::Nmi), Connector::Nomupay => Ok(Self::Nomupay), Connector::Noon => Ok(Self::Noon), Connector::Novalnet => Ok(Self::Novalnet), Connector::Nuvei => Ok(Self::Nuvei), Connector::Opennode => Ok(Self::Opennode), Connector::Paybox => Ok(Self::Paybox), Connector::Payme => Ok(Self::Payme), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), Connector::Paystack => Ok(Self::Paystack), Connector::Payu => Ok(Self::Payu), Connector::Placetopay => Ok(Self::Placetopay), Connector::Powertranz => Ok(Self::Powertranz), Connector::Prophetpay => Ok(Self::Prophetpay), Connector::Rapyd => Ok(Self::Rapyd), Connector::Razorpay => Ok(Self::Razorpay), Connector::Riskified => Ok(Self::Riskified), Connector::Shift4 => Ok(Self::Shift4), Connector::Signifyd => Ok(Self::Signifyd), Connector::Square => Ok(Self::Square), Connector::Stax => Ok(Self::Stax), Connector::Stripe => Ok(Self::Stripe), Connector::Stripebilling => Ok(Self::Stripebilling), Connector::Trustpay => Ok(Self::Trustpay), Connector::Tsys => Ok(Self::Tsys), Connector::Volt => Ok(Self::Volt), Connector::Wellsfargo => Ok(Self::Wellsfargo), Connector::Wise => Ok(Self::Wise), Connector::Worldline => Ok(Self::Worldline), Connector::Worldpay => Ok(Self::Worldpay), Connector::Xendit => Ok(Self::Xendit), Connector::Zen => Ok(Self::Zen), Connector::Plaid => Ok(Self::Plaid), Connector::Zsl => Ok(Self::Zsl), Connector::Recurly => Ok(Self::Recurly), Connector::Getnet => Ok(Self::Getnet), Connector::Hipay => Ok(Self::Hipay), Connector::Inespay => Ok(Self::Inespay), Connector::Redsys => Ok(Self::Redsys), Connector::CtpMastercard | Connector::Gpayments | Connector::Juspaythreedsserver | Connector::Netcetera | Connector::Taxjar | Connector::Threedsecureio | Connector::CtpVisa => Err("Invalid conversion. Not a routable connector"), } } } <file_sep path="hyperswitch/crates/common_enums/src/connector_enums.rs" crate="common_enums" role="use_site"> use std::collections::HashSet; use utoipa::ToSchema; pub use super::enums::{PaymentMethod, PayoutType}; pub use crate::PaymentMethodType; #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] /// RoutableConnectors are the subset of Connectors that are eligible for payments routing pub enum RoutableConnectors { Adyenplatform, #[cfg(feature = "dummy_connector")] #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] DummyConnector1, #[cfg(feature = "dummy_connector")] #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] DummyConnector2, #[cfg(feature = "dummy_connector")] #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] DummyConnector3, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_test")] #[strum(serialize = "stripe_test")] DummyConnector4, #[cfg(feature = "dummy_connector")] #[serde(rename = "adyen_test")] #[strum(serialize = "adyen_test")] DummyConnector5, #[cfg(feature = "dummy_connector")] #[serde(rename = "checkout_test")] #[strum(serialize = "checkout_test")] DummyConnector6, #[cfg(feature = "dummy_connector")] #[serde(rename = "paypal_test")] #[strum(serialize = "paypal_test")] DummyConnector7, Aci, Adyen, Airwallex, // Amazonpay, Authorizedotnet, Bankofamerica, Billwerk, Bitpay, Bambora, Bamboraapac, Bluesnap, Boku, Braintree, Cashtocode, Chargebee, Checkout, Coinbase, Coingate, Cryptopay, Cybersource, Datatrans, Deutschebank, Digitalvirgo, Dlocal, Ebanx, Elavon, // Facilitapay, Fiserv, Fiservemea, Fiuu, Forte, Getnet, Globalpay, Globepay, Gocardless, Hipay, Helcim, Iatapay, Inespay, Itaubank, Jpmorgan, Klarna, Mifinity, Mollie, Moneris, Multisafepay, Nexinets, Nexixpay, Nmi, Nomupay, Noon, Novalnet, Nuvei, // Opayo, added as template code for future usage Opennode, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Paybox, Payme, Payone, Paypal, Paystack, Payu, Placetopay, Powertranz, Prophetpay, Rapyd, Razorpay, Recurly, Redsys, Riskified, Shift4, Signifyd, Square, Stax, Stripe, Stripebilling, // Taxjar, Trustpay, // Thunes // Tsys, Tsys, // UnifiedAuthenticationService, Volt, Wellsfargo, // Wellsfargopayout, Wise, Worldline, Worldpay, Xendit, Zen, Plaid, Zsl, } // A connector is an integration to fulfill payments #[derive( Clone, Copy, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::VariantNames, strum::EnumIter, strum::Display, strum::EnumString, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum Connector { Adyenplatform, #[cfg(feature = "dummy_connector")] #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] DummyConnector1, #[cfg(feature = "dummy_connector")] #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] DummyConnector2, #[cfg(feature = "dummy_connector")] #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] DummyConnector3, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_test")] #[strum(serialize = "stripe_test")] DummyConnector4, #[cfg(feature = "dummy_connector")] #[serde(rename = "adyen_test")] #[strum(serialize = "adyen_test")] DummyConnector5, #[cfg(feature = "dummy_connector")] #[serde(rename = "checkout_test")] #[strum(serialize = "checkout_test")] DummyConnector6, #[cfg(feature = "dummy_connector")] #[serde(rename = "paypal_test")] #[strum(serialize = "paypal_test")] DummyConnector7, Aci, Adyen, Airwallex, // Amazonpay, Authorizedotnet, Bambora, Bamboraapac, Bankofamerica, Billwerk, Bitpay, Bluesnap, Boku, Braintree, Cashtocode, Chargebee, Checkout, Coinbase, Coingate, Cryptopay, CtpMastercard, CtpVisa, Cybersource, Datatrans, Deutschebank, Digitalvirgo, Dlocal, Ebanx, Elavon, // Facilitapay, Fiserv, Fiservemea, Fiuu, Forte, Getnet, Globalpay, Globepay, Gocardless, Gpayments, Hipay, Helcim, Inespay, Iatapay, Itaubank, Jpmorgan, Juspaythreedsserver, Klarna, Mifinity, Mollie, Moneris, Multisafepay, Netcetera, Nexinets, Nexixpay, Nmi, Nomupay, Noon, Novalnet, Nuvei, // Opayo, added as template code for future usage Opennode, Paybox, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Payme, Payone, Paypal, Paystack, Payu, Placetopay, Powertranz, Prophetpay, Rapyd, Razorpay, Recurly, Redsys, Shift4, Square, Stax, Stripe, Stripebilling, Taxjar, Threedsecureio, //Thunes, Trustpay, Tsys, // UnifiedAuthenticationService, Volt, Wellsfargo, // Wellsfargopayout, Wise, Worldline, Worldpay, Signifyd, Plaid, Riskified, Xendit, Zen, Zsl, } impl Connector { #[cfg(feature = "payouts")] pub fn supports_instant_payout(self, payout_method: Option<PayoutType>) -> bool { matches!( (self, payout_method), (Self::Paypal, Some(PayoutType::Wallet)) | (_, Some(PayoutType::Card)) | (Self::Adyenplatform, _) | (Self::Nomupay, _) ) } #[cfg(feature = "payouts")] pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Bank))) } #[cfg(feature = "payouts")] pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Card))) } #[cfg(feature = "payouts")] pub fn is_payout_quote_call_required(self) -> bool { matches!(self, Self::Wise) } #[cfg(feature = "payouts")] pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (Self::Paypal, _)) } #[cfg(feature = "payouts")] pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool { matches!(self, Self::Stripe | Self::Nomupay) } pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool { matches!( (self, payment_method), (Self::Airwallex, _) | (Self::Deutschebank, _) | (Self::Globalpay, _) | (Self::Jpmorgan, _) | (Self::Moneris, _) | (Self::Paypal, _) | (Self::Payu, _) | ( Self::Trustpay, PaymentMethod::BankRedirect | PaymentMethod::BankTransfer ) | (Self::Iatapay, _) | (Self::Volt, _) | (Self::Itaubank, _) ) } pub fn supports_file_storage_module(self) -> bool { matches!(self, Self::Stripe | Self::Checkout) } pub fn requires_defend_dispute(self) -> bool { matches!(self, Self::Checkout) } pub fn is_separate_authentication_supported(self) -> bool { match self { #[cfg(feature = "dummy_connector")] Self::DummyConnector1 | Self::DummyConnector2 | Self::DummyConnector3 | Self::DummyConnector4 | Self::DummyConnector5 | Self::DummyConnector6 | Self::DummyConnector7 => false, Self::Aci // Add Separate authentication support for connectors | Self::Adyen | Self::Adyenplatform | Self::Airwallex // | Self::Amazonpay | Self::Authorizedotnet | Self::Bambora | Self::Bamboraapac | Self::Bankofamerica | Self::Billwerk | Self::Bitpay | Self::Bluesnap | Self::Boku | Self::Braintree | Self::Cashtocode | Self::Chargebee | Self::Coinbase | Self::Coingate | Self::Cryptopay | Self::Deutschebank | Self::Digitalvirgo | Self::Dlocal | Self::Ebanx | Self::Elavon // | Self::Facilitapay | Self::Fiserv | Self::Fiservemea | Self::Fiuu | Self::Forte | Self::Getnet | Self::Globalpay | Self::Globepay | Self::Gocardless | Self::Gpayments | Self::Hipay | Self::Helcim | Self::Iatapay | Self::Inespay | Self::Itaubank | Self::Jpmorgan | Self::Juspaythreedsserver | Self::Klarna | Self::Mifinity | Self::Mollie | Self::Moneris | Self::Multisafepay | Self::Nexinets | Self::Nexixpay | Self::Nomupay | Self::Novalnet | Self::Nuvei | Self::Opennode | Self::Paybox | Self::Payme | Self::Payone | Self::Paypal | Self::Paystack | Self::Payu | Self::Placetopay | Self::Powertranz | Self::Prophetpay | Self::Rapyd | Self::Recurly | Self::Redsys | Self::Shift4 | Self::Square | Self::Stax | Self::Stripebilling | Self::Taxjar // | Self::Thunes | Self::Trustpay | Self::Tsys // | Self::UnifiedAuthenticationService | Self::Volt | Self::Wellsfargo // | Self::Wellsfargopayout | Self::Wise | Self::Worldline | Self::Worldpay | Self::Xendit | Self::Zen | Self::Zsl | Self::Signifyd | Self::Plaid | Self::Razorpay | Self::Riskified | Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::CtpVisa | Self::Noon | Self::Stripe | Self::Datatrans => false, Self::Checkout | Self::Nmi |Self::Cybersource => true, } } pub fn is_pre_processing_required_before_authorize(self) -> bool { matches!(self, Self::Airwallex) } pub fn get_payment_methods_supporting_extended_authorization(self) -> HashSet<PaymentMethod> { HashSet::new() } pub fn get_payment_method_types_supporting_extended_authorization( self, ) -> HashSet<PaymentMethodType> { HashSet::new() } pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool { matches!(self, Self::Adyenplatform) } /// Validates if dummy connector can be created /// Dummy connectors can be created only if dummy_connector feature is enabled in the configs #[cfg(feature = "dummy_connector")] pub fn validate_dummy_connector_create(self, is_dummy_connector_enabled: bool) -> bool { matches!( self, Self::DummyConnector1 | Self::DummyConnector2 | Self::DummyConnector3 | Self::DummyConnector4 | Self::DummyConnector5 | Self::DummyConnector6 | Self::DummyConnector7 ) && !is_dummy_connector_enabled } } /// Convert the RoutableConnectors to Connector impl From<RoutableConnectors> for Connector { fn from(routable_connector: RoutableConnectors) -> Self { match routable_connector { RoutableConnectors::Adyenplatform => Self::Adyenplatform, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector1 => Self::DummyConnector1, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector2 => Self::DummyConnector2, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector3 => Self::DummyConnector3, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector4 => Self::DummyConnector4, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector5 => Self::DummyConnector5, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector6 => Self::DummyConnector6, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector7 => Self::DummyConnector7, RoutableConnectors::Aci => Self::Aci, RoutableConnectors::Adyen => Self::Adyen, RoutableConnectors::Airwallex => Self::Airwallex, RoutableConnectors::Authorizedotnet => Self::Authorizedotnet, RoutableConnectors::Bankofamerica => Self::Bankofamerica, RoutableConnectors::Billwerk => Self::Billwerk, RoutableConnectors::Bitpay => Self::Bitpay, RoutableConnectors::Bambora => Self::Bambora, RoutableConnectors::Bamboraapac => Self::Bamboraapac, RoutableConnectors::Bluesnap => Self::Bluesnap, RoutableConnectors::Boku => Self::Boku, RoutableConnectors::Braintree => Self::Braintree, RoutableConnectors::Cashtocode => Self::Cashtocode, RoutableConnectors::Chargebee => Self::Chargebee, RoutableConnectors::Checkout => Self::Checkout, RoutableConnectors::Coinbase => Self::Coinbase, RoutableConnectors::Cryptopay => Self::Cryptopay, RoutableConnectors::Cybersource => Self::Cybersource, RoutableConnectors::Datatrans => Self::Datatrans, RoutableConnectors::Deutschebank => Self::Deutschebank, RoutableConnectors::Digitalvirgo => Self::Digitalvirgo, RoutableConnectors::Dlocal => Self::Dlocal, RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, // RoutableConnectors::Facilitapay => Self::Facilitapay, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, RoutableConnectors::Forte => Self::Forte, RoutableConnectors::Getnet => Self::Getnet, RoutableConnectors::Globalpay => Self::Globalpay, RoutableConnectors::Globepay => Self::Globepay, RoutableConnectors::Gocardless => Self::Gocardless, RoutableConnectors::Helcim => Self::Helcim, RoutableConnectors::Iatapay => Self::Iatapay, RoutableConnectors::Itaubank => Self::Itaubank, RoutableConnectors::Jpmorgan => Self::Jpmorgan, RoutableConnectors::Klarna => Self::Klarna, RoutableConnectors::Mifinity => Self::Mifinity, RoutableConnectors::Mollie => Self::Mollie, RoutableConnectors::Moneris => Self::Moneris, RoutableConnectors::Multisafepay => Self::Multisafepay, RoutableConnectors::Nexinets => Self::Nexinets, RoutableConnectors::Nexixpay => Self::Nexixpay, RoutableConnectors::Nmi => Self::Nmi, RoutableConnectors::Nomupay => Self::Nomupay, RoutableConnectors::Noon => Self::Noon, RoutableConnectors::Novalnet => Self::Novalnet, RoutableConnectors::Nuvei => Self::Nuvei, RoutableConnectors::Opennode => Self::Opennode, RoutableConnectors::Paybox => Self::Paybox, RoutableConnectors::Payme => Self::Payme, RoutableConnectors::Payone => Self::Payone, RoutableConnectors::Paypal => Self::Paypal, RoutableConnectors::Paystack => Self::Paystack, RoutableConnectors::Payu => Self::Payu, RoutableConnectors::Placetopay => Self::Placetopay, RoutableConnectors::Powertranz => Self::Powertranz, RoutableConnectors::Prophetpay => Self::Prophetpay, RoutableConnectors::Rapyd => Self::Rapyd, RoutableConnectors::Razorpay => Self::Razorpay, RoutableConnectors::Recurly => Self::Recurly, RoutableConnectors::Redsys => Self::Redsys, RoutableConnectors::Riskified => Self::Riskified, RoutableConnectors::Shift4 => Self::Shift4, RoutableConnectors::Signifyd => Self::Signifyd, RoutableConnectors::Square => Self::Square, RoutableConnectors::Stax => Self::Stax, RoutableConnectors::Stripe => Self::Stripe, RoutableConnectors::Stripebilling => Self::Stripebilling, RoutableConnectors::Trustpay => Self::Trustpay, RoutableConnectors::Tsys => Self::Tsys, RoutableConnectors::Volt => Self::Volt, RoutableConnectors::Wellsfargo => Self::Wellsfargo, RoutableConnectors::Wise => Self::Wise, RoutableConnectors::Worldline => Self::Worldline, RoutableConnectors::Worldpay => Self::Worldpay, RoutableConnectors::Zen => Self::Zen, RoutableConnectors::Plaid => Self::Plaid, RoutableConnectors::Zsl => Self::Zsl, RoutableConnectors::Xendit => Self::Xendit, RoutableConnectors::Inespay => Self::Inespay, RoutableConnectors::Coingate => Self::Coingate, RoutableConnectors::Hipay => Self::Hipay, } } } impl TryFrom<Connector> for RoutableConnectors { type Error = &'static str; fn try_from(connector: Connector) -> Result<Self, Self::Error> { match connector { Connector::Adyenplatform => Ok(Self::Adyenplatform), #[cfg(feature = "dummy_connector")] Connector::DummyConnector1 => Ok(Self::DummyConnector1), #[cfg(feature = "dummy_connector")] Connector::DummyConnector2 => Ok(Self::DummyConnector2), #[cfg(feature = "dummy_connector")] Connector::DummyConnector3 => Ok(Self::DummyConnector3), #[cfg(feature = "dummy_connector")] Connector::DummyConnector4 => Ok(Self::DummyConnector4), #[cfg(feature = "dummy_connector")] Connector::DummyConnector5 => Ok(Self::DummyConnector5), #[cfg(feature = "dummy_connector")] Connector::DummyConnector6 => Ok(Self::DummyConnector6), #[cfg(feature = "dummy_connector")] Connector::DummyConnector7 => Ok(Self::DummyConnector7), Connector::Aci => Ok(Self::Aci), Connector::Adyen => Ok(Self::Adyen), Connector::Airwallex => Ok(Self::Airwallex), Connector::Authorizedotnet => Ok(Self::Authorizedotnet), Connector::Bankofamerica => Ok(Self::Bankofamerica), Connector::Billwerk => Ok(Self::Billwerk), Connector::Bitpay => Ok(Self::Bitpay), Connector::Bambora => Ok(Self::Bambora), Connector::Bamboraapac => Ok(Self::Bamboraapac), Connector::Bluesnap => Ok(Self::Bluesnap), Connector::Boku => Ok(Self::Boku), Connector::Braintree => Ok(Self::Braintree), Connector::Cashtocode => Ok(Self::Cashtocode), Connector::Chargebee => Ok(Self::Chargebee), Connector::Checkout => Ok(Self::Checkout), Connector::Coinbase => Ok(Self::Coinbase), Connector::Coingate => Ok(Self::Coingate), Connector::Cryptopay => Ok(Self::Cryptopay), Connector::Cybersource => Ok(Self::Cybersource), Connector::Datatrans => Ok(Self::Datatrans), Connector::Deutschebank => Ok(Self::Deutschebank), Connector::Digitalvirgo => Ok(Self::Digitalvirgo), Connector::Dlocal => Ok(Self::Dlocal), Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), // Connector::Facilitapay => Ok(Self::Facilitapay), Connector::Fiserv => Ok(Self::Fiserv), Connector::Fiservemea => Ok(Self::Fiservemea), Connector::Fiuu => Ok(Self::Fiuu), Connector::Forte => Ok(Self::Forte), Connector::Globalpay => Ok(Self::Globalpay), Connector::Globepay => Ok(Self::Globepay), Connector::Gocardless => Ok(Self::Gocardless), Connector::Helcim => Ok(Self::Helcim), Connector::Iatapay => Ok(Self::Iatapay), Connector::Itaubank => Ok(Self::Itaubank), Connector::Jpmorgan => Ok(Self::Jpmorgan), Connector::Klarna => Ok(Self::Klarna), Connector::Mifinity => Ok(Self::Mifinity), Connector::Mollie => Ok(Self::Mollie), Connector::Moneris => Ok(Self::Moneris), Connector::Multisafepay => Ok(Self::Multisafepay), Connector::Nexinets => Ok(Self::Nexinets), Connector::Nexixpay => Ok(Self::Nexixpay), Connector::Nmi => Ok(Self::Nmi), Connector::Nomupay => Ok(Self::Nomupay), Connector::Noon => Ok(Self::Noon), Connector::Novalnet => Ok(Self::Novalnet), Connector::Nuvei => Ok(Self::Nuvei), Connector::Opennode => Ok(Self::Opennode), Connector::Paybox => Ok(Self::Paybox), Connector::Payme => Ok(Self::Payme), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), Connector::Paystack => Ok(Self::Paystack), Connector::Payu => Ok(Self::Payu), Connector::Placetopay => Ok(Self::Placetopay), Connector::Powertranz => Ok(Self::Powertranz), Connector::Prophetpay => Ok(Self::Prophetpay), Connector::Rapyd => Ok(Self::Rapyd), Connector::Razorpay => Ok(Self::Razorpay), Connector::Riskified => Ok(Self::Riskified), Connector::Shift4 => Ok(Self::Shift4), Connector::Signifyd => Ok(Self::Signifyd), Connector::Square => Ok(Self::Square), Connector::Stax => Ok(Self::Stax), Connector::Stripe => Ok(Self::Stripe), Connector::Stripebilling => Ok(Self::Stripebilling), Connector::Trustpay => Ok(Self::Trustpay), Connector::Tsys => Ok(Self::Tsys), Connector::Volt => Ok(Self::Volt), Connector::Wellsfargo => Ok(Self::Wellsfargo), Connector::Wise => Ok(Self::Wise), Connector::Worldline => Ok(Self::Worldline), Connector::Worldpay => Ok(Self::Worldpay), Connector::Xendit => Ok(Self::Xendit), Connector::Zen => Ok(Self::Zen), Connector::Plaid => Ok(Self::Plaid), Connector::Zsl => Ok(Self::Zsl), Connector::Recurly => Ok(Self::Recurly), Connector::Getnet => Ok(Self::Getnet), Connector::Hipay => Ok(Self::Hipay), Connector::Inespay => Ok(Self::Inespay), Connector::Redsys => Ok(Self::Redsys), Connector::CtpMastercard | Connector::Gpayments | Connector::Juspaythreedsserver | Connector::Netcetera | Connector::Taxjar | Connector::Threedsecureio | Connector::CtpVisa => Err("Invalid conversion. Not a routable connector"), } } } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=use_site,macro_def use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> <|fim_prefix|> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/common_enums/src/connector_enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> common_enums macro=DieselEnumText roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum RoutableConnectors { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/common_enums/src/connector_enums.rs" crate="common_enums" role="use_site"> <|fim_prefix|> pub enum RoutableConnectors { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=DieselEnum roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=DieselEnum roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=DieselEnum roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=DieselEnum roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=DieselEnum roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/router_derive/src/lib.rs" crate="router_derive" role="macro_def"> pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router_derive/src/lib.rs<|crate|> diesel_models macro=DieselEnum roles=macro_def,use_site use=attribute item=file pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/diesel_models/src/enums.rs" crate="diesel_models" role="use_site"> <|fim_prefix|> pub enum RoutingAlgorithmKind { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods